Archive

Archive for the ‘Uncategorized’ Category

Remove #AWS Credentials cached by #AWSToolkit

This issue affects Windows users, specifically Visual Studio with the AWS Toolkit installed, and it happens when the AWS Toolkit keeps a copy of old AWS credentials that may no longer be valid.

Here is the scenario.

I set up my AWS credentials using AWS configure, this stores the credentials in a file /user/.aws/credentials – I run Visual Studio, and AWS Toolkit keeps a copy of the credentials. Now, I decide to change the AWS credentials, and using the CLI again, I change the credentials on my machine. The CLI works fine, but Visual Studio is using old credentials, and breaks with an error like;

UnrecognizedClientException – The security token included in the request is invalid

at Amazon.Runtime.Internal.HttpErrorResponseExceptionHandler.HandleException(IExecutionContext executionContext, HttpErrorResponseException exception)
at Amazon.Runtime.Internal.ExceptionHandler`1.Handle(IExecutionContext executionContext, Exception exception)
at Amazon.Runtime.Internal.ErrorHandler.ProcessException(IExecutionContext executionContext, Exception exception)
at Amazon.Runtime.Internal.ErrorHandler.InvokeAsync[T](IExecutionContext executionContext)
at Amazon.Runtime.Internal.CallbackHandler.InvokeAsync[T](IExecutionContext executionContext)
at Amazon.Runtime.Internal.EndpointDiscoveryHandler.InvokeAsync[T](IExecutionContext executionContext)
at Amazon.Runtime.Internal.EndpointDiscoveryHandler.InvokeAsync[T](IExecutionContext executionContext)
at Amazon.Runtime.Internal.CredentialsRetriever.InvokeAsync[T](IExecutionContext executionContext)
at Amazon.Runtime.Internal.RetryHandler.InvokeAsync[T](IExecutionContext executionContext)
at Amazon.Runtime.Internal.RetryHandler.InvokeAsync[T](IExecutionContext executionContext)
at Amazon.Runtime.Internal.CallbackHandler.InvokeAsync[T](IExecutionContext executionContext)
at Amazon.Runtime.Internal.CallbackHandler.InvokeAsync[T](IExecutionContext executionContext)
at Amazon.Runtime.Internal.ErrorCallbackHandler.InvokeAsync[T](IExecutionContext executionContext)
at Amazon.Runtime.Internal.MetricsHandler.InvokeAsync[T](IExecutionContext executionContext)

Well, what how to clear the AWSToolkit cache?

Go to

C:\Users\<your user>\AppData\Local\AWSToolkit

and

erase RegisteredAccounts.json

Then restart Visual Studio, and it will find the correct credentials.

Categories: Uncategorized

Alternative to rotating proxies using #AWS API Gateway and #FireProx

There are many services out there, that can give you a rotating proxy service, using a pool of IP addresses, and some of those pools are probably huge. However, here is an interesting approach discovered by Black Hills Information Security that can use AWS API Gateway as a proxy – A proxy that can only be used for one domain, but it rotates the Egress IP address with every request, and you’re using the IP address pool of an entire AWS Availability zone, and technically, you could set up multiple region end points, if you wanted.

So, the solution is called FireProx, and it’s a Python script that sets up an API gateway for you, such that you can make a request to the AWS gateway URL, and the request will be proxied to the destination,

For example;

https://3eqe4t8sxh.execute-api.eu-west-1.amazonaws.com/fireprox/

Goes to “http://icanhazip.com&#8221; – and nearly demonstrates the rotating proxy IP.

To run it, in Windows (Assuming you have Python and VirtualEnv already installed, and AWS already configured):

git clone https://github.com/ustayready/fireprox
cd fireprox
py -m virtualenv -p python3 .
env\Scripts\activate
pip install -r requirements.txt
python fire.py

Then you can create an api gateway using;

python fire.py --command create --url http://icanhazip.com

The GitHub repo is here; so you can verify the source yourself; https://github.com/ustayready/fireprox

Categories: Uncategorized

Determine a user’s country from their IP in #Javascript

If you need a quick check to determine the country of origin of your website visitor using Javascript, then you can use this little snippet of code using the ip-api service;

  var s = document.createElement("script");
  s.src = "http://ip-api.com/json/?callback=ipFound";
  document.body.appendChild(s);
  function ipFound(ipInfo)
  {
	  alert("You are from " + ipInfo.countryCode);
  }

It’s free to use (for non-commercial purposes), and uses no API Key, It’s using JSONP which is supported on most browsers.

Evidently, if you want more foolproof check, then a server-side check would be better, but it’s good to help guide your users to the right country, or preselect some options for them.

Categories: Uncategorized

AWSLambdaFullAccess becomes AWSLambda_FullAccess

The AWS Toolkit for Visual Studio is great, when it works, but when it breaks, it’s a headache. The AWS Toolkit allows you publish your .NET code to AWS Lambda, with a API gateway already setup for you. It does this with a Cloud Formation stack under the hood, and this encapsulates the steps required to publish the Lambda, connect and configure the API gateway, and give you a public URL to play with.

Now, as of the 1st of March 2021, AWS deprecated the policy AWSLambdaFullAccess and replaced it with the similarly named AWSLambda_FullAccess – which is one underscore, but perhaps an hour of work to change.

First off, the error isn’t very helpful;

AspNetCoreFunctionRoleUPDATE_FAILED1 validation error detected: Value ‘AWSLambdaFullAccess‘ at ‘policyArn’ failed to satisfy constraint: Member must have length greater than or equal to 20 (Service: AmazonIdentityManagement; Status Code: 400; Error Code: ValidationError; Request ID: cec22c28-2aae-4de8-9ef7-51880070081d; Proxy: null)

What does that mean, well, after googling, I found out that the policy had been deprecated, and set about editing the cloudformation stack.

So, I went into AWS, found the cloud formation stack, and tried to edit the template. But I couldn’t edit it, just make a copy of it (perhaps there is a better way here!, please leave a comment!) – and then I created a new Cloud Formation Stack, with a new name, but with the policy AWSLambdaFullAccess changed to AWSLambda_FullAccess

Back in Visual Studio, I clicked on the “Publish to AWS Lambda”, then selected the new stack from the drop down list, and pressed publish. Finally it worked!

It gave me a new API endpoint URL, which I didn’t want, and I had to reconfigure some permissions and the VPC that I had applied to the lambda manually.

Not a good experience at all, and I would really like to slap the AWS engineer that for making that change.


Following up from this post yesterday, I figured out how to update the existing Cloud Formation Stack, which importantly, allowed me to keep the same URL, and maintained the VPC and custom permissions.

So, First off, you go into the stack – press the Template tab, then View in Designer.

If you flick the language settings from JSON to YAML and back again, you get the JSON in a pretty format, so you can search for the AWSLambdaFullAccess and replace it with AWSLambda_FullAccess – Once finished, you can save the template locally, which you will upload again later., by pressing File > Save

Back in the Stack, press the Change Sets tab, and press Create Change set, select “Replace current template”, then “upload a template file”, and upload the file from the previous step. Press Next > Next > Next, then create change set.

Once you’ve done that, you’ll need to execute the change set.

However, if you’re like me, your stack will be in an invalid state, which you have to fix first, so you need to rollback the changeset, while ignoring the error that stopped the automatic rollback in the first place.

(from: https://aws.amazon.com/premiumsupport/knowledge-center/cloudformation-update-rollback-failed/)

If you want to skip FAILED resources during rollback, complete the following:

1.    From the Stack name column, select the stack that’s stuck in UPDATE_ROLLBACK_FAILED status.

2.    Choose Stack Actions, and then choose Continue update rollback.

3.    In the Continue update rollback dialog box, expand Advanced troubleshooting.

4.    In the Resources to skip – optional section, select the resources that you want to skip.

5.    Choose Continue update rollback.

Once you’ve successfully rolled back the stack, then you can execute the change set, and your cloudformation stack should be back working again, and you can deploy again from Visual Studio.

Categories: Uncategorized

Server side templating in .NET Core with #Razor

Templating is extremely common, and is used to separate the data (often in JSON) from the presentation layer, which can either be on the client side (Mustache, Angular, Vue, React) , or on the server side (ASP.NET, Razor, etc.)

The template is typically hard-coded so that the data changes, but the template used to render that data in a presentable way is fixed. However, in certain circumstances, you may want to offer the ability to the user to change the template.

This could be in a situation where you want to offer full flexibility in presentation to the end-customer. Perhaps you want them to be able to style their own webpage, user portal, or report, or pdf. In this case, allowing both a dynamic template applied to dynamic data can offer much more flexibility.

This approach demonstrates the use of Razor, which is used commonly in modern .NET web apps, although it requires a very technical user, and could potentially cause some security issues, if the end user were to inject malicious code into the template.

So, without further Ado, let’s take a look at this project.

First, I’ll define some data as follows;

{
  "Company": "Microsoft",
  "Directors": [
    "Bill Gates",
    "Steve Ballmer"
  ]
}

Which I save as data.json, and set the property to “Copy always” in Visual Studio.

Then I define a template like so;

@Model.Company, has @Model.Directors.Count directors which are: @foreach (var Director in Model.Directors) { @String.Concat(Director," ") }

Which is designed to read “Microsoft has 2 directors which are Bill Gates Steve Ballmer”, this would be saved as “template.html” in the project.

Now, I Install the relevant NuGet packages, and usings;

using Newtonsoft.Json.Linq;  // Install-Package Newtonsoft.JSON
using RazorEngine; // Install-Package RazorEngine.NetCore
using RazorEngine.Templating;

And finally, put it all together as follows;

var data = File.ReadAllText("data.json");
var template = File.ReadAllText("template.html");
dynamic model = JObject.Parse(data);
var result =
Engine.Razor.RunCompile(
    template,
    "template",
    null,
    (object)model);
Console.WriteLine(result);

Viola!

The github repo for this project is available here: https://github.com/infiniteloopltd/RazorTemplating

Categories: Uncategorized

Generate a #PDF from #HTML on Raspberry PI (.NET Core)

TL; DR; Here is the github repo: https://github.com/infiniteloopltd/hello-world-pi/blob/master/program.cs

This was an academic exercise for me, but in case you ever wanted to generate PDFs on a Raspberry pi, here is some code to do so in C# (.NET Core).

The core of the operation is wkhtmltopdf, which you can install on Raspberry pi (ubuntu), by simply typing

"apt-get wkhtmltopdf"

Then I created a C# app, based on the code from WkHtmlDriver that simply opens the executable, and redirects the standard input / output and error streams to the host application, and feeds it HTML to be encoded, and captures the output stream.

The code then converts the output stream to a byte array, and then dumps this to disk.

Here’s the final code:

var proc = new Process {
    StartInfo = new ProcessStartInfo {
        FileName = "wkhtmltopdf",
            Arguments = "-q - -",
            UseShellExecute = false,
            RedirectStandardOutput = true,
            RedirectStandardError = true,
            RedirectStandardInput = true,
            CreateNoWindow = true
    }
};
proc.Start();
using(var sIn = proc.StandardInput) {
    sIn.WriteLine("hello world");
}
var ms = new MemoryStream();
var sOut = proc.StandardOutput.BaseStream;
sOut.CopyTo(ms);
if (ms.Length == 0) {
    string error = proc.StandardError.ReadToEnd();
    throw new Exception(error);
}
proc.WaitForExit();
Console.WriteLine(ms.Length + " bytes written");
File.WriteAllBytes("hello.pdf", ms.ToArray());

Categories: Uncategorized

NHTSA Recall #API using VIN numbers C# #VIN #ODI

The US Government maintains a vehicle safety recall list, in the event of a vehicle safety defect that requires vehicles to be recalled to the manufacturer for part replacement. This can be searched by make / model / year, but not currently by VIN.

We’ve just launched a Recall API based on VIN numbers, which is called in this format;

https://www.regcheck.org.uk/api/recalls.aspx/1FAFP34361W244896

Where 1FAFP34361W244896 is a 2001 Ford Focus that is under recall, the API requires basic authentication, and you can get a username and password by registering on the website http://www.vehicleregistrationapi.com/

JSON is returned in the following format;

{
   "Count":14,
   "Message":"Results returned successfully",
   "Results":[
      {
         "Manufacturer":"FORD MOTOR COMPANY",
         "NHTSACampaignNumber":"01V258000",
         "ReportReceivedDate":"\/Date(997243200000-0400)\/",
         "Component":"VISIBILITY:WINDSHIELD WIPER/WASHER:MOTOR",
         "Summary":"VEHICLE DESCRIPTION:  PASSENGER CARS, SPORT UTILITY VEHICLES, AND LIGHT AND MEDIUM DUTY PICKUP TRUCKS.   A SWITCH LOCATED IN THE PLASTIC COVER OF THE WIPER MOTOR GEAR CASE COULD MALFUNCTION AND OVERHEAT, POTENTIALLY RESULTING IN LOSS OF INTERMITTENT WIPER FUNCTION, LOSS OF WIPER PARK FUNCTION, COMPLETE LOSS OF WIPER FUNCTION, OR IGNITION OF THE PLASTIC COVER MATERIAL.  SWITCH MALFUNCTION IS MOST LIKELY TO OCCUR WHEN THE INTERMITTENT SETTING OF THE WIPERS IS BEING USED, OR WHEN SNOW OR ICE OBSTRUCTS THE BLADES FROM RETURNING TO THE \"PARKED\" POSITION AT THE BOTTOM OF THE WINDSHIELD.  THESE VEHICLES WERE BUILT AT THE FOLLOWING ASSEMBLY PLANTS:   ATLANTA PLANT FROM 2/11/00 THROUGH 7/31/00;  CHICAGO PLANT FROM 2/14/00 THROUGH 8/4/00;  KANSAS CITY PLANT FROM 2/26/00 TO 9/4/00;  KENTUCKY TRUCK PLANT FROM 2/18/00 TO 8/31/00;  MICHIGAN TRUCK PLANT FROM 2/23/00 THROUGH 8/3/00;  NORFOLK PLANT FROM 2/21/00 THROUGH 7/27/00;  WAYNE STAMPING AND ASSEMBLY PLANT FROM 2/25/00 THROUGH 8/15/00; AND WIXOM PLANT FROM 2/15/00 THROUGH 8/8/00.",
         "Conequence":"LOSS OF VISIBILITY WHILE DRIVING INCREASES THE RISK OF A CRASH.",
         "Remedy":"DEALERS WILL INSPECT THE DATE CODE ON THE WIPER MOTOR.  MOTORS BUILT WITH THE SUSPECT TIME FRAME WILL HAVE THE WIPER MOTOR GEAR CASE COVER REPLACED.  OWNER NOTIFICATION BEGAN AUGUST 20, 2001.  OWNERS WHO TAKE THEIR VEHICLES TO AN AUTHORIZED DEALER ON AN AGREED UPON SERVICE DATE AND DO NOT RECEIVE THE FREE REMEDY WITHIN A REASONABLE TIME SHOULD CONTACT FORD AT 1-866-436-7332.",
         "Notes":"ALSO CONTACT THE NATIONAL HIGHWAY TRAFFIC SAFETY ADMINISTRATION'S AUTO SAFETY HOTLINE AT 1-888-DASH-2-DOT (1-888-327-4236).",
         "ModelYear":"2001",
         "Make":"FORD",
         "Model":"FOCUS"
      },
      {
         "Manufacturer":"FORD MOTOR COMPANY",
         "NHTSACampaignNumber":"01V108000",
         "ReportReceivedDate":"\/Date(985755600000-0500)\/",
         "Component":"SEATS:FRONT ASSEMBLY:RECLINER",
         "Summary":"PM CERTAIN SEDANS AND WAGONS, THE SEAT BACK RECLINER HANDLE SPRING COULD HAVE BEEN DAMAGED DURING AN IN-PROCESS TEST AND THE OCCUPANT MAY NOTICE A CHUCKING, OR PERCEIVED LOOSENESS OF THE FRONT SEAT BACK, OR THE SEAT BACK COULD UNEXPECTEDLY RECLINE.",
         "Conequence":"IF THE SEAT BACK UNEXPECTEDLY RECLINES WHILE THE CAR IS BEING DRIVEN, IT COULD RESULT IN LOSS OF VEHICLE CONTROL.",
         "Remedy":"DEALERS WILL REPLACE THE SEAT BACK RECLINER HANDLE SPRING FOR THE DRIVER AND FRONT PASSENGER SEATS.  OWNER NOTIFICATION BEGAN APRIL 3, 2001.   OWNERS WHO TAKE THEIR VEHICLES TO AN AUTHORIZED DEALER ON AN AGREED UPON SERVICE DATE AND DO NOT RECEIVE THE FREE REMEDY WITHIN A REASONABLE TIME SHOULD CONTACT FORD AT 1-800-392-3673.",
         "Notes":"ALSO CONTACT THE NATIONAL HIGHWAY TRAFFIC SAFETY ADMINISTRATION'S AUTO SAFETY HOTLINE AT 1-888-DASH-2-DOT (1-888-327-4236).",
         "ModelYear":"2001",
         "Make":"FORD",
         "Model":"FOCUS"
      },
      {
         "Manufacturer":"FORD MOTOR COMPANY",
         "NHTSACampaignNumber":"01I017000",
         "ReportReceivedDate":"\/Date(1007010000000-0500)\/",
         "Component":"WHEELS:LUGS/NUTS/BOLTS",
         "Summary":"THIS IS NOT A SAFETY RECALL IN ACCORDANCE WITH THE SAFETY ACT.  HOWEVER, IT IS DEEMED A SAFETY IMPROVEMENT CAMPAIGN BY THE AGENCY.   VEHICLE DESCRIPTION:  2000-2001 FORD FOCUS PASSENGER VEHICLES, ORIGINALLY SOLD IN OR CURRENTLY REGISTERED IN THE STATES OF CONNECTICUT, DELAWARE, ILLINOIS, INDIANA, IOWA, KENTUCKY, MAINE, MARYLAND, MASSACHUSETTS, MICHIGAN, MINNESOTA, MISSOURI, NEW HAMPSHIRE, NEW JERSEY, NEW YORK, OHIOM, PENNSYLVANIA, RHODE ISLAND, VERMONT, WEST VIRGINIA, AND WISCONSIN.  IN HIGH CORROSION AREAS, WHERE SALT IS USED ON ROADWAYS IN THE WINTER, THE REAR WHEEL BEARING SEAL RACE CAN EXPERIENCE SURFACE CORROSION.  IF THIS CONDITION OCCURS, THE WHEEL BEARING SEALS COULD BECOME DAMAGED AND ALLOW CONTAMINATION TO ENTER THE WHEEL BEARINGS.",
         "Conequence":"THE WHEEL BEARINGS COULD PREMATURELY WEAR AND CAUSE A NOTICEABLE NOISE.  IF NOT REPAIRED, THIS CONDITION COULD PROGRESS TO THE POINT WHERE THE WHEEL BEGINS TO WOBBLE.",
         "Remedy":"DEALERS WILL REPLACE THE REAR WHEEL BEARINGS AT NO COST TO THE CONSUMER.  ADDITIONAL BEARING SEALS WILL ALSO BE INSTALLED TO ENSURE A SMOOTH RIDE.  THIS PROGRAM WILL BE IN EFFECT UNTIL DECEMBER 31, 2002, REGARDLESS OF MILEAGE.  EVEN IF THE VEHICLE HAS ALREADY BEEN SERVICED UNDER RECALL CAMPAIGN 00S31, FORD HAS TAKEN ADDITIONAL STEPS TO KEEP THE WHEEL BEARINGS IN TOP SHAPE.\r\nOWNERS CAN CONTACT FORD AT  1-866-436-7332, CONCERNING THIS PROGRAM.",
         "Notes":"FORD HAS DECIDED TO CONDUCT A SERVICE CAMPAIGN TO REPLACE THE REAR WHEEL BEARINGS.   OWNERS CAN CONTACT FORD AT  1-866-436-7332, CONCERNING THIS PROGRAM.",
         "ModelYear":"2001",
         "Make":"FORD",
         "Model":"FOCUS"
      },
      {
         "Manufacturer":"FORD MOTOR COMPANY",
         "NHTSACampaignNumber":"00V418000",
         "ReportReceivedDate":"\/Date(976770000000-0500)\/",
         "Component":"SEATS:FRONT ASSEMBLY:RECLINER",
         "Summary":"VEHICLE DESCRIPTION:  STATION WAGONS AND 3-DOOR VEHICLES.  THE SUBJECT VEHICLES HAVE A FOLDING 60/40 SECOND SEAT THAT BECOMES A LOAD FLOOR IN THE FOLDED POSITION. WHEN THE 60% PORTION OF THE SEAT IS FOLDED DOWN AND A LOAD IS APPLIED TO THE FRONT EDGE OF THE LOAD FLOOR, THE OUTBOARD HINGE PIVOT COULD DISENGAGE FROM THE HINGE.",
         "Conequence":"IF THE SEAT IS THEN RETURNED TO THE UPRIGHT POSITION WITHOUT RE-ENGAGING THE HINGE PIVOT, THE SEAT AND SEAT BELTS MAY NOT PROVIDE THE INTENDED LEVEL OF PERFORMANCE IN THE EVENT OF A CRASH.",
         "Remedy":"DEALERS WILL INSTALL A REVISED SEAT BACK HINGE PIVOT.",
         "Notes":"OWNER NOTIFICATION IBEGAN JANUARY 24, 2001.  OWNERS WHO TAKE THEIR VEHICLES TO AN AUTHORIZED DEALER ON AN AGREED UPON SERVICE DATE AND DO NOT RECEIVE THE FREE REMEDY WITHIN A REASONABLE TIME SHOULD CONTACT FORD AT 1-800-392-3673.  ALSO CONTACT THE NATIONAL HIGHWAY TRAFFIC SAFETY ADMINISTRATION'S AUTO SAFETY HOTLINE AT 1-888-DASH-2-DOT (1-888-327-4236).",
         "ModelYear":"2001",
         "Make":"FORD",
         "Model":"FOCUS"
      },
      {
         "Manufacturer":"FORD MOTOR COMPANY",
         "NHTSACampaignNumber":"02V288000",
         "NHTSAActionNumber":"EA02014 | PE02032",
         "ReportReceivedDate":"\/Date(1036558800000-0500)\/",
         "Component":"ELECTRICAL SYSTEM:12V/24V/48V BATTERY:CABLES | ELECTRICAL SYSTEM:12V/24V/48V BATTERY:CABLES",
         "Summary":"CERTAIN PASSENGER VEHICLES EQUIPPED WITH ZETEC ENGINES, LOOSE OR BROKEN ATTACHMENTS AND MISROUTED BATTERY CABLES COULD LEAD TO CABLE INSULATION DAMAGE.",
         "Conequence":"THIS, IN TURN, COULD CAUSE THE BATTERY CABLES TO SHORT RESULTING IN HEAT DAMAGE TO THE CABLES.  BESIDES HEAT DAMAGE, THE \"CHECK ENGINE\" LIGHT MAY ILLUMINATE, THE VEHICLE MAY FAIL TO START, OR SMOKE, MELTING, OR FIRE COULD ALSO OCCUR.",
         "Remedy":"DEALERS WILL INSPECT THE BATTERY CABLES FOR THE CONDITION OF THE CABLE INSULATION AND PROPER TIGHTENING OF THE TERMINAL ENDS.  AS NECESSARY, CABLES WILL BE REROUTED, RETAINING CLIPS INSTALLED, AND DAMAGED BATTERY CABLES REPLACED.   OWNER NOTIFICATION BEGAN FEBRUARY 10, 2003.   OWNERS WHO DO NOT RECEIVE THE FREE REMEDY  WITHIN A REASONABLE TIME SHOULD CONTACT FORD AT 1-866-436-7332.",
         "Notes":"ALSO CONTACT THE NATIONAL HIGHWAY TRAFFIC SAFETY ADMINISTRATION'S AUTO SAFETY HOTLINE AT 1-888-DASH-2-DOT (1-888-327-4236).",
         "ModelYear":"2001",
         "Make":"FORD",
         "Model":"FOCUS"
      },
      {
         "Manufacturer":"FORD MOTOR COMPANY",
         "NHTSACampaignNumber":"02V289000",
         "ReportReceivedDate":"\/Date(1036558800000-0500)\/",
         "Component":"STEERING:LINKAGES",
         "Summary":"CERTAIN PASSENGER VEHICLES HAVE LOOSE PINCH BOLTS THAT SECURE THE LOWER CONTROL ARM TO THE STEERING KNUCKLE HAVE BEEN REPORTED.",
         "Conequence":"LOOSE PINCH BOLTS COULD EXHIBIT NOISE, VIBRATION AND, IN EXTREME CASES IF LEFT UNCORRECTED, SEPARATION OF THE JOINT OR FRACTURE OF THE BALL JOINT STUD, INCREASING THE RISK OF A CRASH.",
         "Remedy":"DEALERS WILL INSPECT THE STEERING KNUCKLE PINCH BOLT FOR TIGHTNESS AND CORRECT AS NECESSARY.  OWNER NOTIFICATION BEGAN FEBRUARY 10, 2003.   OWNERS WHO DO NOT RECEIVE THE FREE REMEDY  WITHIN A REASONABLE TIME SHOULD CONTACT FORD AT 1-866-436-7332.",
         "Notes":"ALSO CONTACT THE NATIONAL HIGHWAY TRAFFIC SAFETY ADMINISTRATION'S AUTO SAFETY HOTLINE AT 1-888-DASH-2-DOT (1-888-327-4236).",
         "ModelYear":"2001",
         "Make":"FORD",
         "Model":"FOCUS"
      },
      {
         "Manufacturer":"FORD MOTOR COMPANY",
         "NHTSACampaignNumber":"03V482000",
         "NHTSAActionNumber":"EA02022",
         "ReportReceivedDate":"\/Date(1069218000000-0500)\/",
         "Component":"FUEL SYSTEM, GASOLINE",
         "Summary":"ON CERTAIN PASSENGER VEHICLES, CONTAMINATION OF THE FILTER IN THE FUEL DELIVERY MODULE (FDM) CAN REDUCE, AND EVENTUALLY BLOCK, THE FLOW OF FUEL TO THE ENGINE.",
         "Conequence":"THIS MAY CAUSE ENGINE HESITATION, LOSS OF POWER, SURGING, AND OTHER SIMILAR  SYMPTOMS.  OVER TIME, THE FILTER MAY BECOME SUFFICIENTLY BLOCKED TO CAUSE THE ENGINE TO STALL, WHICH COULD RESULT IN A CRASH.",
         "Remedy":"THIS ACTION IS DEEMED A SAFETY IMPROVEMENT CAMPAIGN AND IS NOT BEING CONDUCTED UNDER THE SAFETY ACT.  ALL OWNERS WILL BE NOTIFIED OF THE PROBLEM, AND DEALERS WILL REPLACE THE FDM WITH A NEW DESIGN AT NO CHARGE IF THE OWNER REPORTS THAT THE VEHICLE EXHIBITS ANY OF THE IDENTIFIED SYMPTOMS.  THE FREE REPLACEMENT WILL BE AVAILABLE FOR A PERIOD OF 10 YEARS FOLLOWING THE ORIGINAL PURCHASE OF THE VEHICLE, WITH NO MILEAGE LIMIT.  OWNER NOTIFICATION IS EXPECTED TO BEGIN DURING NOVEMBER 2003.  OWNERS SHOULD CONTACT FORD AT 1-800-392-3673.",
         "Notes":"FORD CAMPAIGN NO. 03N01.  CUSTOMERS CAN ALSO CONTACT THE NATIONAL HIGHWAY TRAFFIC SAFETY ADMINISTRATION'S AUTO SAFETY HOTLINE AT 1-888-DASH-2-DOT (1-888-327-4236).",
         "ModelYear":"2001",
         "Make":"FORD",
         "Model":"FOCUS"
      },
      {
         "Manufacturer":"FORD MOTOR COMPANY",
         "NHTSACampaignNumber":"05V030000",
         "NHTSAActionNumber":"EA04023",
         "ReportReceivedDate":"\/Date(1107234000000-0500)\/",
         "Component":"LATCHES/LOCKS/LINKAGES:DOORS:LATCH",
         "Summary":"CERTAIN PASSENGER VEHICLES WITH FOUR OR FIVE DOORS AND ORIGINALLY SOLD IN OR CURRENTLY REGISTERED IN CONNECTICUT, DELAWARE, ILLINOIS, INDIANA, IOWA, MAINE, MARYLAND, MASSACHUSETTS, MICHIGAN, MINNESOTA, MISSOURI, NEW HAMPSHIRE, NEW JERSEY, NEW YORK, OHIO, PENNSYLVANIA, RHODE ISLAND, VERMONT, WEST VIRGINIA, WISCONSIN, AND THE DISTRICT OF COLUMBIA, A BUILD-UP OF CORROSION AT THE PAWL PIVOT AREA OF THE REAR DOOR LATCH CAN CAUSE A BINDING CONDITION OF THE PAWL THAT MAY AFFECT PROPER ENGAGEMENT OF THE PAWL INTO THE CATCH. THE OCCUPANT MAY EXPERIENCE DIFFICULTY OPENING OR CLOSING A REAR DOOR, AND EVENTUALLY THE REAR DOOR MAY NOT LATCH PROPERLY. \r\n",
         "Conequence":"IF NOT LATCHED PROPERLY, THE DOOR MAY OPEN WHILE THE VEHICLE IS IN MOTION.  IF AN OCCUPANT FELL OUT OF THE VEHICLE, PERSONAL INJURIES COULD OCCUR.",
         "Remedy":"DEALERS WILL HAVE A LOWER ROCKER SEAL ADDED TO THE DOOR AND HAVE THE REAR DOOR LATCHES EVALUATED FREE OF CHARGE.  A LATCH THAT PASSES THE EVALUATION WILL BE LUBRICATED TO PREVENT FUTURE CORROSION.  A LATCH THAT DOES NOT PASS THE EVALUATION WILL BE REPLACED.  IN ADDITION, A STICKER WILL BE AFFIXED TO THE REAR DOORS ADVISING THE OWNERS TO USE THE RECOMMENDED LUBRICANT.  THE RECALL BEGAN ON MARCH 9, 2005.  OWNERS MAY CONTACT FORD AT 1-800-392-3673.\r\n",
         "Notes":"FORD RECALL NO. 05S27.    CUSTOMERS MAY ALSO CONTACT THE NATIONAL HIGHWAY TRAFFIC SAFETY ADMINISTRATION'S VEHICLE SAFETY HOTLINE AT 1-888-327-4236 (TTY 1-800-424-9153), OR GO TO HTTP://WWW.SAFERCAR.GOV. ",
         "ModelYear":"2001",
         "Make":"FORD",
         "Model":"FOCUS"
      },
      {
         "Manufacturer":"PRO-A MOTORS, INC.",
         "NHTSACampaignNumber":"06E026000",
         "ReportReceivedDate":"\/Date(1143090000000-0500)\/",
         "Component":"EXTERIOR LIGHTING",
         "Summary":"CERTAIN PRO-A MOTORS CORNER LAMPS, TURN SIGNALS, AND HEADLIGHTS SOLD AS REPLACEMENT LAMPS FOR USE ON CERTAIN PASSENGER VEHICLES LISTED ABOVE.  SOME COMBINATION LAMPS THAT ARE NOT EQUIPPED WITH AMBER SIDE REFLECTORS FAIL TO CONFORM TO FEDERAL MOTOR VEHICLE SAFETY STANDARD NO. 108, LAMPS, REFLECTIVE DEVICES, AND ASSOCIATED EQUIPMENT.",
         "Conequence":"WITHOUT THE AMBER REFLECTORS, THE VEHICLE WILL BE POORLY ILLUMINATED, POSSIBLY RESULTING IN A VEHICLE CRASH WITHOUT WARNING.",
         "Remedy":"PRO-A MOTORS WILL NOTIFY OWNERS AND OFFER TO REPURCHASE THE LAMPS.  THE RECALL BEGAN ON APRIL 3, 2006.  OWNERS MAY CONTACT PRO-A MOTORS AT 323-838-2988.",
         "Notes":"THIS RECALL ONLY PERTAINS TO PRO-A MOTORS AFTERMARKET LAMPS AND HAS NO RELATION TO ANY ORIGINAL EQUIPMENT INSTALLED ON THE LISTED PASSENGER VEHICLES.  FOR MORE INFORMATION ON THE LAMP MODEL NUMBERS, CLICK ON DOCUMENT SEARCH AND VIEW DOCUMENT TITLED \"LAMP MODEL NUMBERS.\"  CUSTOMERS MAY CONTACT THE NATIONAL HIGHWAY TRAFFIC SAFETY ADMINISTRATION'S VEHICLE SAFETY HOTLINE AT 1-888-327-4236 (TTY: 1-800-424-9153); OR GO TO HTTP://WWW.SAFERCAR.GOV.",
         "ModelYear":"2001",
         "Make":"FORD",
         "Model":"FOCUS"
      },
      {
         "Manufacturer":"CK MOTORSPORT, INC.",
         "NHTSACampaignNumber":"06E049000",
         "ReportReceivedDate":"\/Date(1148443200000-0400)\/",
         "Component":"EXTERIOR LIGHTING",
         "Summary":"CERTAIN CK MOTORSPORTS COMBINATION HEADLIGHTS, CLEAR CORNER, BUMPER, AND SIDE MARKER LIGHTS SOLD AS REPLACEMENT LAMPS FOR USE ON THE PASSENGER VEHICLES LISTED ABOVE.  SOME COMBINATION LAMPS THAT ARE NOT EQUIPPED WITH AMBER SIDE REFLECTORS FAIL TO CONFORM TO FEDERAL MOTOR VEHICLE SAFETY STANDARD NO. 108, LAMPS, REFLECTIVE DEVICES, AND ASSOCIATED EQUIPMENT.",
         "Conequence":"WITHOUT THE AMBER REFLECTORS, THE VEHICLE WILL BE POORLY ILLUMINATED, POSSIBLY RESULTING IN A VEHICLE CRASH WITHOUT WARNING.",
         "Remedy":"CK MOTORSPORT WILL NOTIFY OWNERS AND REPLACE THE NONCOMPLIANT LAMPS FREE OF CHARGE.  THE RECALL BEGAN ON JULY 1, 2006.  OWNERS MAY CONTACT CK MOTORSPORT AT 1-909-610-7211.",
         "Notes":"THIS RECALL ONLY PERTAINS TO AFTERMARKET REPLACEMENT EQUIPMENT AND HAS NO RELATION TO ANY ORIGINAL EQUIPMENT INSTALLED ON VEHICLES MANUFACTURED BY THE VEHICLE MANUFACTURERS.  FOR MORE INFORMATION ON THE LAMP MODEL NUMBERS, CLICK ON DOCUMENT SEARCH AND VIEW DOCUMENT TITLED \"LAMP MODEL NUMBERS.\"  CUSTOMERS MAY CONTACT THE NATIONAL HIGHWAY TRAFFIC SAFETY ADMINISTRATION'S VEHICLE SAFETY HOTLINE AT 1-888-327-4236 (TTY: 1-800-424-9153); OR GO TO HTTP://WWW.SAFERCAR.GOV.\r\n",
         "ModelYear":"2001",
         "Make":"FORD",
         "Model":"FOCUS"
      },
      {
         "Manufacturer":"K2 MOTOR CORPORATION",
         "NHTSACampaignNumber":"08E050000",
         "ReportReceivedDate":"\/Date(1218427200000-0400)\/",
         "Component":"EXTERIOR LIGHTING:HEADLIGHTS",
         "Summary":"K2 MOTOR IS RECALLING 1,921 AFTERMARKET HEADLAMPS OF VARIOUS MODELS SOLD FOR USE ON THE ABOVE LISTED VEHICLES.  THESE HEADLAMPS ARE MISSING THE AMBER SIDE REFLEX REFLECTOR WHICH FAILS TO CONFORM WITH THE REQUIREMENTS OF FEDERAL MOTOR VEHICLE SAFETY STANDARD NO. 108, \"LAMPS, REFLECTIVE DEVICES, AND ASSOCIATED EQUIPMENT.\"",
         "Conequence":"WITHOUT THE AMBER SIDE REFLEX REFLECTORS, THE LIGHTING VISIBILITY MAY BE AFFECTED, POSSIBLY RESULTING IN A VEHICLE CRASH.",
         "Remedy":"K2 MOTOR WILL NOTIFY OWNERS AND OFFER A FULL REFUND.  THE RECALL BEGAN ON DECEMEBER 17, 2008.  OWNERS MAY CONTACT K2 MOTOR AT 1-909-839-2992.",
         "Notes":"THIS RECALL ONLY PERTAINS TO AFTERMARKET REPLACEMENT EQUIPMENT AND HAS NO RELATION TO ANY ORIGINAL EQUIPMENT INSTALLED ON VEHICLES MANUFACTURED BY HONDA, FORD, OR CHRYSLER LLC.   CUSTOMERS MAY CONTACT THE NATIONAL HIGHWAY TRAFFIC SAFETY ADMINISTRATION'S VEHICLE SAFETY HOTLINE AT 1-888-327-4236 (TTY: 1-800-424-9153); OR GO TO HTTP://WWW.SAFERCAR.GOV.",
         "ModelYear":"2001",
         "Make":"FORD",
         "Model":"FOCUS"
      },
      {
         "Manufacturer":"SABERSPORT",
         "NHTSACampaignNumber":"09E012000",
         "ReportReceivedDate":"\/Date(1239076800000-0400)\/",
         "Component":"EXTERIOR LIGHTING",
         "Summary":"SABERSPORT IS RECALLING 16,270 COMBINATION CORNER AND BUMPER LAMP ASSEMBLIES OF VARIOUS PART NUMBERS SOLD FOR USE AS AFTERMARKET EQUIPMENT FOR VARIOUS PASSENGER VEHICLES.  THESE HEADLAMPS FAIL TO CONFORM TO THE REQUIREMENTS OF FEDERAL MOTOR VEHICLE SAFETY STANDARD NO. 108, \"LAMPS, REFLECTIVE DEVICES, AND ASSOCIATED EQUIPMENT.\"  THESE LAMPS DO NOT CONTAIN THE REQUIRED AMBER SIDE REFLECTORS.",
         "Conequence":"DECREASED LIGHTING VISIBILITY MAY RESULT IN A VEHICLE CRASH.",
         "Remedy":"SABERSPORT WILL NOTIFY OWNERS AND OFFER A FULL REFUND FOR THE NONCOMPLIANT COMBINATION LAMPS.  THE SAFETY RECALL BEGAN ON MAY 11, 2009.  OWNERS MAY CONTACT SABERSPORT AT 1-909-598-7589.  ",
         "Notes":"THIS RECALL ONLY PERTAINS TO AFTERMARKET REPLACEMENT EQUIPMENT AND HAS NO RELATION TO ANY ORIGINAL EQUIPMENT INSTALLED ON VEHICLES PRODUCED BY THE VEHICLE MANUFACTURER.  IN ORDER TO DETERMINE IF YOUR AFTERMARKET LAMP ASSEMBLY IS AFFECTED BY THIS NONCOMPLIANCE, PLEASE REVIEW THE LIST OF MODEL NUMBERS PROVIDED TO US BY SABERSPORT.  THE LIST CAN BE FOUND UNDER \"DOCUMENT SEARCH\" LOCATED AT THE BOTTOM OF YOUR SCREEN.  OWNERS MAY ALSO CONTACT THE NATIONAL HIGHWAY TRAFFIC SAFETY ADMINISTRATION'S VEHICLE SAFETY HOTLINE AT 1-888-327-4236 (TTY 1-800-424-9153), OR GO TO <A HREF=HTTP://WWW.SAFERCAR.GOV>HTTP://WWW.SAFERCAR.GOV</A> .",
         "ModelYear":"2001",
         "Make":"FORD",
         "Model":"FOCUS"
      },
      {
         "Manufacturer":"DOPE, INC.",
         "NHTSACampaignNumber":"09E025000",
         "ReportReceivedDate":"\/Date(1242014400000-0400)\/",
         "Component":"EXTERIOR LIGHTING:HEADLIGHTS",
         "Summary":"DOPE, INC. IS RECALLING 42,540 COMBINATION CORNER AND BUMPER LAMP ASSEMBLIES OF VARIOUS PART NUMBERS SOLD FOR USE AS AFTERMARKET EQUIPMENT FOR VARIOUS PASSENGER VEHICLES.  THESE HEADLAMPS FAIL TO CONFORM TO THE REQUIREMENTS OF FEDERAL MOTOR VEHICLE SAFETY STANDARD NO. 108, \"LAMPS, REFLECTIVE DEVICES, AND ASSOCIATED EQUIPMENT.\"  THESE LAMPS DO NOT CONTAIN THE REQUIRED AMBER SIDE REFLECTORS.",
         "Conequence":"DECREASED LIGHTING VISIBILITY MAY RESULT IN A VEHICLE CRASH.",
         "Remedy":"DOPE, INC. WILL NOTIFY OWNERS AND OFFER A FULL REFUND FOR THE NONCOMPLIANT COMBINATION LAMPS.  THE SAFETY RECALL BEGAN ON JULY 28, 2009.  OWNERS MAY CONTACT DOPE, INC. AT 1-626-272-1798.  ",
         "Notes":"THIS RECALL ONLY PERTAINS TO AFTERMARKET REPLACEMENT EQUIPMENT AND HAS NO RELATION TO ANY ORIGINAL EQUIPMENT INSTALLED ON VEHICLES PRODUCED BY THE VEHICLE MANUFACTURER.  IN ORDER TO DETERMINE IF YOUR AFTERMARKET LAMP ASSEMBLY IS AFFECTED BY THIS NONCOMPLIANCE, PLEASE REVIEW THE LIST OF MODEL NUMBERS PROVIDED TO US BY DOPE, INC.  THE LIST CAN BE FOUND UNDER \"DOCUMENT SEARCH\" LOCATED AT THE BOTTOM OF YOUR SCREEN.   \r\nOWNERS MAY ALSO CONTACT THE NATIONAL HIGHWAY TRAFFIC SAFETY ADMINISTRATION'S VEHICLE SAFETY HOTLINE AT 1-888-327-4236 (TTY 1-800-424-9153), OR GO TO <A HREF=HTTP://WWW.SAFERCAR.GOV>HTTP://WWW.SAFERCAR.GOV</A> .",
         "ModelYear":"2001",
         "Make":"FORD",
         "Model":"FOCUS"
      },
      {
         "Manufacturer":"RIDE CONTROL, LLC",
         "NHTSACampaignNumber":"12E007000",
         "ReportReceivedDate":"\/Date(1330059600000-0500)\/",
         "Component":"EQUIPMENT",
         "Summary":"RIDE CONTROL, LLC (RIDE CONTROL) IS RECALLING CERTAIN READYMOUNT ASSEMBLIES, P/N 746641MT AND 746646MT, WITH CORRESPONDING AFTERMARKET CUSTOMER PART NUMBERS: GABRIEL G56944 AND GABRIEL G56945, AND PRIVATELY BRANDED PARTSMASTER WITH PART NUMBERS G68944 AND G68945.  THE READYMOUNT ASSEMBLIES WERE SOLD AS AFTERMARKET SERVICE EQUIPMENT FOR USE ON CERTAIN 2000 THROUGH 2005 FORD FOCUS VEHICLES.  THESE ASSEMBLIES WERE ASSEMBLED WITH A NUT WITHOUT THE NECESSARY WASHER.  THE ABSENCE OF THE WASHER CAN ALLOW THE READYMOUNT ASSEMBLY TO PULL APART THE TOP MOUNT.",
         "Conequence":"IF THE ASSEMBLY SEPARATES DURING INSTALLATION, IT COULD RESULT IN INJURY TO THE INSTALLER.  IF THE ASSEMBLY SEPARATES WHILE THE VEHICLE IS IN MOTION, IT COULD RESULT IN SECONDARY DAMAGE TO THE VEHICLE AND POSSIBLY RESULT IN A VEHICLE CRASH.",
         "Remedy":"RIDE CONTROL WILL NOTIFY OWNERS AND WILL SET UP PROCEDURES TO INSPECT, REPAIR, AND/OR REPLACE THE AFFECTED PARTS WITHOUT CHARGE TO THE OWNER.  THE SAFETY RECALL BEGAN ON MARCH 30, 2012.  OWNERS MAY CONTACT RIDE CONTROL AT 1-800-999-3903.",
         "Notes":"OWNERS MAY ALSO CONTACT THE NATIONAL HIGHWAY TRAFFIC SAFETY ADMINISTRATION'S VEHICLE SAFETY HOTLINE AT 1-888-327-4236 (TTY 1-800-424-9153), OR GO TO <A HREF=HTTP://WWW.SAFERCAR.GOV>HTTP://WWW.SAFERCAR.GOV</A> .",
         "ModelYear":"2001",
         "Make":"FORD",
         "Model":"FOCUS"
      }
   ]
}
Categories: Uncategorized

AWS #Transcribe Speech to Text using C#

AWS has a transcribe service which converts audio containing speech to text. It is very tightly integrated with the AWS ecosystem, so it’s probably best used for systems that are already using AWS for other services – specifically, S3 for storage of audio, and perhaps Cloudwatch and Lambda for post processing.

So, the Transcribe service takes an audio file that is already in an S3 bucket with Amazon, and produces text output, which is placed in another bucket. The process is asynchronous, so it’s best to have another event (i.e. Cloudwatch + Lambda) dealing with the output.

First off, you need the Nuget package “Install-Package AWSSDK.TranscribeService” installed for your project. You should also have your local dev environment setup to access AWS via the CLI (aws configure). You don’t have to do that last step, but the code below assumes you have done this.

var client = new AmazonTranscribeServiceClient( RegionEndpoint.EUWest1);

var job = client.StartTranscriptionJobAsync(new StartTranscriptionJobRequest
{
	LanguageCode = LanguageCode.EnUS,
	Media = new Media
	{
		MediaFileUri = "s3://audioBucket/message.mp3"
	},
	MediaFormat = MediaFormat.Mp3,
	OutputBucketName = "aws.serverless.2",
	TranscriptionJobName = "message"
}).Result;

Here, we specify the input S3 Uri, which is an Mp3 file, in US English. I also specify the output bucket, and the name of the file.

This will run, and return immediately. At some time in the future, a file will appear in the output bucket with contents such as;

{
   "jobName":"hotline2",
   "accountId":"005445879168",
   "results":{
      "transcripts":[
         {
            "transcript":"thank you for Collins in his bank, the first American bank designed for international customers. Please leave your message and we will return your call shortly."
         }
      ],
      "items":[
         {
            "start_time":"0.44",
            "end_time":"0.79",
            "alternatives":[
               {
                  "confidence":"1.0",
                  "content":"thank"
               }
            ],
            "type":"pronunciation"
         },
         {
            "start_time":"0.79",
            "end_time":"0.88",
            "alternatives":[
               {
                  "confidence":"1.0",
                  "content":"you"
               }
            ],
            "type":"pronunciation"
         },
         {
            "start_time":"0.88",
            "end_time":"1.01",
            "alternatives":[
               {
                  "confidence":"1.0",
                  "content":"for"
               }
            ],
            "type":"pronunciation"
         },
         {
            "start_time":"1.01",
            "end_time":"1.52",
            "alternatives":[
               {
                  "confidence":"0.9214",
                  "content":"Collins"
               }
            ],
            "type":"pronunciation"
         },
         {
            "start_time":"1.52",
            "end_time":"1.65",
            "alternatives":[
               {
                  "confidence":"0.9884",
                  "content":"in"
               }
            ],
            "type":"pronunciation"
         },
         {
            "start_time":"1.65",
            "end_time":"1.82",
            "alternatives":[
               {
                  "confidence":"0.9662",
                  "content":"his"
               }
            ],
            "type":"pronunciation"
         },
         {
            "start_time":"1.82",
            "end_time":"2.48",
            "alternatives":[
               {
                  "confidence":"1.0",
                  "content":"bank"
               }
            ],
            "type":"pronunciation"
         },
         {
            "alternatives":[
               {
                  "confidence":"0.0",
                  "content":","
               }
            ],
            "type":"punctuation"
         },
         {
            "start_time":"2.51",
            "end_time":"2.77",
            "alternatives":[
               {
                  "confidence":"1.0",
                  "content":"the"
               }
            ],
            "type":"pronunciation"
         },
         {
            "start_time":"2.78",
            "end_time":"3.12",
            "alternatives":[
               {
                  "confidence":"1.0",
                  "content":"first"
               }
            ],
            "type":"pronunciation"
         },
         {
            "start_time":"3.12",
            "end_time":"3.63",
            "alternatives":[
               {
                  "confidence":"1.0",
                  "content":"American"
               }
            ],
            "type":"pronunciation"
         },
         {
            "start_time":"3.63",
            "end_time":"3.99",
            "alternatives":[
               {
                  "confidence":"0.996",
                  "content":"bank"
               }
            ],
            "type":"pronunciation"
         },
         {
            "start_time":"4.0",
            "end_time":"4.58",
            "alternatives":[
               {
                  "confidence":"1.0",
                  "content":"designed"
               }
            ],
            "type":"pronunciation"
         },
         {
            "start_time":"4.58",
            "end_time":"4.74",
            "alternatives":[
               {
                  "confidence":"1.0",
                  "content":"for"
               }
            ],
            "type":"pronunciation"
         },
         {
            "start_time":"4.74",
            "end_time":"5.39",
            "alternatives":[
               {
                  "confidence":"0.9987",
                  "content":"international"
               }
            ],
            "type":"pronunciation"
         },
         {
            "start_time":"5.39",
            "end_time":"6.16",
            "alternatives":[
               {
                  "confidence":"0.9995",
                  "content":"customers"
               }
            ],
            "type":"pronunciation"
         },
         {
            "alternatives":[
               {
                  "confidence":"0.0",
                  "content":"."
               }
            ],
            "type":"punctuation"
         },
         {
            "start_time":"6.54",
            "end_time":"6.94",
            "alternatives":[
               {
                  "confidence":"1.0",
                  "content":"Please"
               }
            ],
            "type":"pronunciation"
         },
         {
            "start_time":"6.94",
            "end_time":"7.12",
            "alternatives":[
               {
                  "confidence":"1.0",
                  "content":"leave"
               }
            ],
            "type":"pronunciation"
         },
         {
            "start_time":"7.12",
            "end_time":"7.26",
            "alternatives":[
               {
                  "confidence":"1.0",
                  "content":"your"
               }
            ],
            "type":"pronunciation"
         },
         {
            "start_time":"7.26",
            "end_time":"7.86",
            "alternatives":[
               {
                  "confidence":"1.0",
                  "content":"message"
               }
            ],
            "type":"pronunciation"
         },
         {
            "start_time":"7.87",
            "end_time":"8.06",
            "alternatives":[
               {
                  "confidence":"1.0",
                  "content":"and"
               }
            ],
            "type":"pronunciation"
         },
         {
            "start_time":"8.06",
            "end_time":"8.17",
            "alternatives":[
               {
                  "confidence":"1.0",
                  "content":"we"
               }
            ],
            "type":"pronunciation"
         },
         {
            "start_time":"8.17",
            "end_time":"8.36",
            "alternatives":[
               {
                  "confidence":"1.0",
                  "content":"will"
               }
            ],
            "type":"pronunciation"
         },
         {
            "start_time":"8.36",
            "end_time":"8.78",
            "alternatives":[
               {
                  "confidence":"0.5229",
                  "content":"return"
               }
            ],
            "type":"pronunciation"
         },
         {
            "start_time":"8.78",
            "end_time":"8.95",
            "alternatives":[
               {
                  "confidence":"1.0",
                  "content":"your"
               }
            ],
            "type":"pronunciation"
         },
         {
            "start_time":"8.95",
            "end_time":"9.33",
            "alternatives":[
               {
                  "confidence":"1.0",
                  "content":"call"
               }
            ],
            "type":"pronunciation"
         },
         {
            "start_time":"9.34",
            "end_time":"10.05",
            "alternatives":[
               {
                  "confidence":"1.0",
                  "content":"shortly"
               }
            ],
            "type":"pronunciation"
         },
         {
            "alternatives":[
               {
                  "confidence":"0.0",
                  "content":"."
               }
            ],
            "type":"punctuation"
         }
      ]
   },
   "status":"COMPLETED"
}

As you can see from the result, it can make some errors, for example, here it used the world “Collins” instead of “Calling”, so the process is not perfect. However, the word-by-word breakdown is really useful, for any other post-processing you may want to do.

This would be excellent for generating subtitles from movie audio, for example.

Categories: Uncategorized

Using #Delphi to call a JSON based #API with basic authentication.

Delphi is quite an old programming language, and has been around since 1995. It’s not really one of the “cool kids” when it comes to programming. However, there is nothing stopping it interoperating with modern REST APIs, which this blog post will show.

So, first off, I downloaded the community edition of Delphi from Embarcadero, and started, directly after a “Hello World”, to make a request to a service that returns my external IP address. Just a simple HTTP GET, but that’s the first step.

So far so simple. I make a crazy call out to CoInitializeEx which does some COM initialization (COM – oh dear). Anyway, then I create a TidHTTP object, which comes from the Indy Project (https://www.indyproject.org/) and then makes a simple GET request, and prints the output to console.

In the above example, I am using an API from http://www.placaapi.com/ – which is a Brazilian vehicle lookup service. you need a username and password, which can be obtained free of charge from the website.

I create an Authentication object, and set the username and password, then I make a HTTP GET request as before.

After I receive the JSON, I pass this to TJSonObject, and read the Description Node from the JSON – There are plenty more fields here, but this is the easiest to display.

For those who want to copy/paste the code – it’s below;

program helloWorld;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  SysUtils, IdHTTP, ActiveX, IdAuthentication, System.JSON;

var
  HTTP: TIdHTTP;  // Create the Indy HTTP Library https://www.indyproject.org/
  Buffer: String;
  JSonValue:TJSonValue;
  Description: string;
  Registration: string;

begin
  try
    // Enter the car registration here
    Registration :=  'BYP6404';
    // https://docs.microsoft.com/en-us/windows/win32/api/combaseapi/nf-combaseapi-coinitializeex
    CoInitializeEx(nil, COINIT_MULTITHREADED);
    HTTP := TIdHTTP.Create;
    HTTP.Request.BasicAuthentication:= true;
    HTTP.Request.Authentication := TIdBasicAuthentication.Create;
    HTTP.Request.Authentication.Username := '***USERNAME HERE***';
    HTTP.Request.Authentication.Password := '***PASSWORD HERE***';
    // Below is the API endpoint for Brazil, can be replaced with any country.
    Buffer := HTTP.Get('http://www.placaapi.com/api/json.aspx/CheckBrazil/' + Registration);
    //Writeln(Buffer); // Uncomment to see full result
    JsonValue := TJSonObject.ParseJSONValue(Buffer);
    // Read the Vehicle Decription
    Description := JsonValue.GetValue<string>('Description');
    Writeln(Description);
  except
    on E: Exception do
        Writeln(E.ClassName, ': ', E.Message); // Show any error
  end;
  readln; // pause on completion
end.

Categories: Uncategorized

Getting #AWS #Lambda timeout value at runtime in C#

If you have a Lambda function in C#, and you have a process that must complete before Amazon kills the process, say in the classic bank transfer example, where you debit one account and credit another. Both actions need to be taken atomically, or else the process should be rolled back.

In this case, you can’t have AWS killing your lambda function due to lack of time remaining, in mid-transaction. In this case, you’d have one account missing money, and no money in the payee account. In this case, it would be better to get a forewarning, that gives you X seconds to rollback the transaction, so that at least, you’re back to where you started.

So, what’s the magic command:

     var context = (ILambdaContext) HttpContext.Items["LambdaContext"];

This gives you an ILambdaContext Object, that contains data similar to the following;


{
   "FunctionName":"HelloWorld-AspNetCoreFunction-1T4MMT4XYY3IJ",
   "FunctionVersion":"$LATEST",
   "LogGroupName":"/aws/lambda/HelloWorld-AspNetCoreFunction-1T4MMT4XYY3IJ",
   "LogStreamName":"2021/03/01/[$LATEST]36833c138ec040549dfd7aa350f2ca44",
   "MemoryLimitInMB":512,
   "AwsRequestId":"b481c563-a027-43d7-bb8e-841ea0f89cdf",
   "InvokedFunctionArn":"arn:aws:lambda:eu-west-1:005445879168:function:HelloWorld-AspNetCoreFunction-1T4MMT4XYY3IJ",
   "RemainingTime":"00:00:28.6830000",
   "ClientContext":null,
   "Identity":{
      "IdentityId":"",
      "IdentityPoolId":""
   },
   "Logger":{
      
   }
}

Which gives you Remaining Time , and the Memory Limit, along with other values.

For other values relating to the Lambda, you should also check the Environment variables in your code.

Categories: Uncategorized