|

|  How to Integrate Microsoft Azure Cognitive Services with Heroku

How to Integrate Microsoft Azure Cognitive Services with Heroku

January 24, 2025

Discover seamless integration of Azure Cognitive Services into Heroku apps with this concise, step-by-step guide. Unlock advanced AI features today!

How to Connect Microsoft Azure Cognitive Services to Heroku: a Simple Guide

 

Setup Microsoft Azure Cognitive Services

 

  • Sign in to the Azure Portal.
  •  

  • Navigate to the "Create a resource" section and search for "Cognitive Services."
  •  

  • Follow the wizard to create a new Cognitive Services resource. Note the endpoint and key generated.
  •  

  • Ensure you have selected the desired Cognitive Services API, such as Text Analytics, Computer Vision, or Speech.

 

Set Up a Basic Heroku Application

 

  • Ensure you have the Heroku CLI installed. If not, download and install it from the Heroku CLI page.
  •  

  • Create a new directory for your application and navigate into it.
  •  

    mkdir my-heroku-app
    cd my-heroku-app
    

     

  • Initialize a new Git repository in this directory.
  •  

    git init
    

     

  • Create a simple application. For example, a Node.js app might have a `server.js` file that uses Express.
  •  

    // server.js
    const express = require('express');
    const app = express();
    const PORT = process.env.PORT || 3000;
    
    app.get('/', (req, res) => {
      res.send('Hello, World!');
    });
    
    app.listen(PORT, () => {
      console.log(`App is running on port ${PORT}`);
    });
    

     

  • Create a `Procfile` for Heroku.
  •  

    web: node server.js
    

 

Integrate Azure Cognitive Services in Your App

 

  • Install the required SDK for your chosen programming language, such as `@azure/cognitiveservices-textanalytics` for Node.js.
  •  

    npm install @azure/cognitiveservices-textanalytics @azure/ms-rest-js
    

     

  • Use the SDK in your application to call Azure Cognitive Services APIs. Below is an example using the Text Analytics API in Node.js.
  •  

    const { TextAnalyticsClient, AzureKeyCredential } = require('@azure/ai-text-analytics');
    
    const key = '<YOUR_COGNITIVE_SERVICE_KEY>';
    const endpoint = '<YOUR_COGNITIVE_SERVICE_ENDPOINT>';
    
    const textAnalyticsClient = new TextAnalyticsClient(endpoint, new AzureKeyCredential(key));
    
    async function analyzeText(inputText) {
      const results = await textAnalyticsClient.analyzeSentiment([inputText]);
      console.log(`Sentiment: ${results[0].sentiment}`);
    }
    
    analyzeText("I love programming!");
    

 

Configure Environment Variables in Heroku

 

  • Login to your Heroku account and navigate to your app's dashboard.
  •  

  • Click on "Settings" and then "Reveal Config Vars."
  •  

  • Add your Azure Cognitive Services key and endpoint as environment variables.
  •  

  • Update your code to use these environment variables instead of hardcoding the key and endpoint.
  •  

    const key = process.env.AZURE_COGNITIVE_KEY;
    const endpoint = process.env.AZURE_COGNITIVE_ENDPOINT;
    

     

 

Deploy Your Heroku Application

 

  • Commit your changes to Git.
  •  

    git add .
    git commit -m "Add Azure Cognitive Services integration"
    

     

  • Create a new Heroku app.
  •  

    heroku create
    

     

  • Deploy your app to Heroku.
  •  

    git push heroku master
    

     

  • Open your application in a browser.
  •  

    heroku open
    

 

Testing and Monitoring

 

  • Test your application by hitting the endpoint that integrates with Azure Cognitive Services.
  •  

  • Monitor your application using Heroku logs to ensure everything is running smoothly.
  •  

    heroku logs --tail
    

     

 

Omi Necklace

The #1 Open Source AI necklace: Experiment with how you capture and manage conversations.

Build and test with your own Omi Dev Kit 2.

How to Use Microsoft Azure Cognitive Services with Heroku: Usecases

 

Use Case: Language Translation and Sentiment Analysis Web App

 

  • Combine the power of Microsoft Azure Cognitive Services with Heroku to create a sophisticated language translation and sentiment analysis web application. This tool can be particularly useful for multinational corporations aiming to understand customer sentiments from reviews or feedback provided in different languages.

 

Architecture Overview

 

  • Utilize Heroku for hosting the web app, taking advantage of its flexibility, scalability, and easy deployment capabilities.
  •  

  • Integrate Azure Cognitive Services for language translation and sentiment analysis functions.

 

Steps for Implementation

 

  • Deploy a Node.js App on Heroku:
    • Create a new Node.js application utilizing the Express framework to handle HTTP requests and serve web pages.
    • Set up a Git repository and connect it to Heroku using the Heroku CLI for seamless deployment.
  •  

  • Integrate Azure Cognitive Services:
    • Sign up for Azure Cognitive Services and subscribe to the Language Services API for accessing translation and sentiment analysis capabilities.
    • Add the Azure SDK for JavaScript to your project by installing the necessary npm packages.
    • Configure API keys and endpoints within your application to make requests to Azure.
  •  

  • Build the Frontend Interface:
    • Create a user-friendly front end using HTML, CSS, and JavaScript to allow users to input text for translation and sentiment analysis.
  •  

  • Implement Backend Logic:
    • Implement API call functions in Node.js to handle text translation and sentiment analysis by passing data to and from Azure Cognitive Services.
    • Process the results from Azure, such as displaying translated text or visualizing sentiment analysis outcomes.
  •  

  • Deploy and Monitor:
    • Deploy the application on Heroku and validate that all integrations are functioning correctly.
    • Utilize Heroku's monitoring tools to ensure the application runs smoothly under various load conditions.
  •  

  • Regular Updates and Maintenance:
    • Regularly update the Azure SDK and Heroku buildpack to incorporate new features and security patches.
    • Monitor Azure service utilization and adjust the service tier as necessary to optimize costs and performance.

 


const express = require('express');
const axios = require('axios');
const app = express();

app.use(express.json());

app.post('/translate', async (req, res) => {
  const { text, targetLanguage } = req.body;

  try {
    const response = await axios.post(`https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&to=${targetLanguage}`, [{ 'text': text }], {
      headers: {
        'Ocp-Apim-Subscription-Key': process.env.AZURE_SUBSCRIPTION_KEY,
        'Content-Type': 'application/json'
      }
    });
    const translatedText = response.data[0].translations[0].text;
    res.json({ translated: translatedText });
  } catch (error) {
    res.status(500).send('Error translating text.');
  }
});

app.listen(process.env.PORT || 3000, () => {
  console.log('Server is running on port 3000');
});

 

 

Use Case: Real-time Photo Annotation and Analysis Platform

 

  • Leverage Microsoft Azure Cognitive Services in combination with Heroku to create an advanced photo annotation and analysis platform. This application is ideal for media companies, social networks, and photography enthusiasts seeking to gain insights, tag objects, and enhance their photo libraries.

 

Architecture Overview

 

  • Deploy the web application on Heroku for seamless scalability and effortless application management.
  •  

  • Integrate Azure Cognitive Services to perform image analysis, object detection, and OCR (Optical Character Recognition).

 

Steps for Implementation

 

  • Create a Flask Application and Deploy on Heroku:
    • Develop a Flask-based application to handle image uploads and HTTP requests.
    • Establish a Git repository and link it with Heroku using the Heroku CLI for easy deployment workflows.
  •  

  • Set Up Azure Cognitive Services:
    • Register for Azure Cognitive Services and use Computer Vision API to enable image analysis functionalities.
    • Install necessary Python libraries using pip to interact with Azure’s APIs.
    • Configure API credentials within the app for seamless integration with Azure services.
  •  

  • Develop the Frontend for Image Upload and Display:
    • Design a web interface using HTML, CSS, and JavaScript to upload images and display the results of the analysis effectively.
  •  

  • Implement Server-side Logic:
    • Create a Flask route to handle image uploads and make API calls to Azure’s Computer Vision service, processing the image data.
    • Parse and handle responses from Azure, extracting useful metadata like object tags, text (OCR), and image descriptions.
  •  

  • Deployment and Optimization:
    • Deploy the application on Heroku, checking all components to ensure the app functions correctly under real-time conditions.
    • Utilize Heroku’s dashboard and monitoring tools for application performance and make adjustments as necessary.
  •  

  • Ongoing Maintenance and Improvements:
    • Keep the Azure SDK and Heroku configurations up-to-date to utilize new features and fixes.
    • Evaluate the application's performance periodically and adjust Azure service tiers to maintain efficiency and manage costs.

 


from flask import Flask, request, jsonify
import requests
from io import BytesIO

app = Flask(__name__)

@app.route('/analyze', methods=['POST'])
def analyze_photo():
    file = request.files['photo']
    
    response = requests.post(
        'https://<your-region>.api.cognitive.microsoft.com/vision/v3.1/analyze?visualFeatures=Description,Tags',
        headers={
            'Ocp-Apim-Subscription-Key': '<Azure-Subscription-Key>',
            'Content-Type': 'application/octet-stream'
        },
        data=file.read()
    )
    
    analysis = response.json()
    return jsonify(analysis)

if __name__ == '__main__':
    app.run(debug=True, port=3000)

 

Omi App

Fully Open-Source AI wearable app: build and use reminders, meeting summaries, task suggestions and more. All in one simple app.

Github →

Order Friend Dev Kit

Open-source AI wearable
Build using the power of recall

Order Now

Troubleshooting Microsoft Azure Cognitive Services and Heroku Integration

How to set up Azure Cognitive Services API key in Heroku?

 

Set Up Azure API Key in Heroku

 

  • First, add your Azure API Key to Heroku as a config var to keep it safe and separate from your source code.
  •  

  • Access your Heroku dashboard, select your app, and navigate to the "Settings" tab.
  •  

  • Under "Config Vars", click "Reveal Config Vars" and enter a key-value pair where the key is your desired environment variable name (e.g., AZURE_API_KEY), and the value is the actual API key.

 

Update Application Code

 

  • In your application, access the environment variable using process.env in Node.js, os.environ.get in Python, or System.getenv in Java.

 

const azureApiKey = process.env.AZURE_API_KEY;

 

Test the Configuration

 

  • Deploy your code to Heroku and check the logs. Run your app and ensure that it correctly reads the API key from the environment variable.

 

heroku logs --tail

 

Why isn't my Azure Cognitive Services request working on Heroku?

 

Check Network Configurations

 

  • Ensure Heroku's outbound requests are not being blocked by Azure. Heroku may be using dynamic IPs, so consider using a CIDR range for Azure’s trusted IPs.
  • Verify that the correct endpoint URL for your Azure region is being used in your requests.

 

Validate Authentication

 

  • Double-check the Azure API key or token. If using environment variables in Heroku, make sure they are set correctly.
  • Consider using Heroku’s Config Vars feature to securely manage your API credentials.

 

Debug the Code

 

import os
import requests

api_key = os.environ.get("AZURE_API_KEY")
endpoint = "https://your-region.api.cognitive.microsoft.com/"

headers = {'Ocp-Apim-Subscription-Key': api_key}
response = requests.get(endpoint, headers=headers)

print(response.status_code, response.json())

 

Review Heroku Logs

 

  • Use the command `heroku logs --tail` to inspect logs in real-time, which can reveal error messages not visible elsewhere.

 

How to manage Azure Cognitive Services environment variables in Heroku?

 

Set Up Environment Variables

 

  • In Heroku, navigate to the app dashboard and click on "Settings." Under "Config Vars," click "Reveal Config Vars."
  •  

  • Add variables related to Azure Cognitive Services such as `AZURE_SUBSCRIPTION_KEY` and `AZURE_ENDPOINT` by entering them in the key-value fields.

 

Access Variables in Code

 

  • In your Heroku-deployed code, use `process.env.VARIABLE_NAME` to access these variables. For example:

 

const subscriptionKey = process.env.AZURE_SUBSCRIPTION_KEY;
const endpoint = process.env.AZURE_ENDPOINT;

 

Secure Tokens

 

  • Never hard-code environment variables directly in your source code to avoid security risks.

 

Local Development

 

  • For local testing, use a `.env` file with the `dotenv` package. Install via npm:

 

npm install dotenv

 

  • Load variables in your code:

 

require('dotenv').config();

 

  • Create a `.env` file with:

 

AZURE_SUBSCRIPTION_KEY=<your-key>
AZURE_ENDPOINT=<your-endpoint>

 

Consistency Across Environments

 

  • Ensure consistency between local and Heroku environments by using the same variable names.

 

Don’t let questions slow you down—experience true productivity with the AI Necklace. With Omi, you can have the power of AI wherever you go—summarize ideas, get reminders, and prep for your next project effortlessly.

Order Now

Join the #1 open-source AI wearable community

Build faster and better with 3900+ community members on Omi Discord

Participate in hackathons to expand the Omi platform and win prizes

Participate in hackathons to expand the Omi platform and win prizes

Get cash bounties, free Omi devices and priority access by taking part in community activities

Join our Discord → 

OMI NECKLACE + OMI APP
First & only open-source AI wearable platform

a person looks into the phone with an app for AI Necklace, looking at notes Friend AI Wearable recorded a person looks into the phone with an app for AI Necklace, looking at notes Friend AI Wearable recorded
a person looks into the phone with an app for AI Necklace, looking at notes Friend AI Wearable recorded a person looks into the phone with an app for AI Necklace, looking at notes Friend AI Wearable recorded
online meeting with AI Wearable, showcasing how it works and helps online meeting with AI Wearable, showcasing how it works and helps
online meeting with AI Wearable, showcasing how it works and helps online meeting with AI Wearable, showcasing how it works and helps
App for Friend AI Necklace, showing notes and topics AI Necklace recorded App for Friend AI Necklace, showing notes and topics AI Necklace recorded
App for Friend AI Necklace, showing notes and topics AI Necklace recorded App for Friend AI Necklace, showing notes and topics AI Necklace recorded

OMI NECKLACE: DEV KIT
Order your Omi Dev Kit 2 now and create your use cases

Omi Dev Kit 2

Endless customization

OMI DEV KIT 2

$69.99

Make your life more fun with your AI wearable clone. It gives you thoughts, personalized feedback and becomes your second brain to discuss your thoughts and feelings. Available on iOS and Android.

Your Omi will seamlessly sync with your existing omi persona, giving you a full clone of yourself – with limitless potential for use cases:

  • Real-time conversation transcription and processing;
  • Develop your own use cases for fun and productivity;
  • Hundreds of community apps to make use of your Omi Persona and conversations.

Learn more

Omi Dev Kit 2: build at a new level

Key Specs

OMI DEV KIT

OMI DEV KIT 2

Microphone

Yes

Yes

Battery

4 days (250mAH)

2 days (250mAH)

On-board memory (works without phone)

No

Yes

Speaker

No

Yes

Programmable button

No

Yes

Estimated Delivery 

-

1 week

What people say

“Helping with MEMORY,

COMMUNICATION

with business/life partner,

capturing IDEAS, and solving for

a hearing CHALLENGE."

Nathan Sudds

“I wish I had this device

last summer

to RECORD

A CONVERSATION."

Chris Y.

“Fixed my ADHD and

helped me stay

organized."

David Nigh

OMI NECKLACE: DEV KIT
Take your brain to the next level

LATEST NEWS
Follow and be first in the know

Latest news
FOLLOW AND BE FIRST IN THE KNOW

thought to action

team@basedhardware.com

company

careers

events

invest

privacy

products

omi

omi dev kit

personas

resources

apps

bounties

affiliate

docs

github

help