|

|  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.

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 →

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