File size: 4,275 Bytes
d25f863
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
from flask import Flask, render_template, request, jsonify
import requests
from dotenv import load_dotenv
import os
import json

# import namespaces
from azure.core.credentials import AzureKeyCredential
from azure.ai.language.questionanswering import QuestionAnsweringClient

from azure.ai.translation.text import *
from azure.ai.translation.text.models import InputTextItem

app = Flask(__name__)

# Get Configuration Settings
load_dotenv()
# Settings for QnA
ai_endpoint = os.getenv('AI_SERVICE_ENDPOINT')
ai_key = os.getenv('AI_SERVICE_KEY')
ai_project_name = os.getenv('QA_PROJECT_NAME')
ai_deployment_name = os.getenv('QA_DEPLOYMENT_NAME')
# SEttings for Translator
translator_endpoint = os.getenv('TRANSLATOR_ENDPOINT')
translator_region = os.getenv('TRANSLATOR_REGION')
translator_key = os.getenv('TRANSLATOR_KEY')

# Create client using endpoint and key
credential = AzureKeyCredential(ai_key)
ai_client = QuestionAnsweringClient(endpoint=ai_endpoint, credential=credential)

@app.route('/')
def home():
    return render_template('index.html')  # HTML file for the web interface

@app.route('/ask', methods=['POST'])
def ask_bot():
    user_question = request.json.get("question", "")
    
    if not user_question:
        return jsonify({"error": "No question provided"}), 400

    # Detect the language of the input text
    detected_language  = detect_language(user_question)

    # If the detected language is not English, translate the question to English; else continue to get the answer
    if detected_language != 'en':
        # Translate the question into English
        translated_question = translate_text(user_question, 'en')    
        try:
            response = ai_client.get_answers(question=translated_question,
                                            project_name=ai_project_name,
                                            deployment_name=ai_deployment_name)
            
            bot_response = response.answers[0].answer if response.answers else "No response from bot"

            # Translate the answer back to the original language
            translated_answer = translate_text(response.answers[0].answer, detected_language)
            return jsonify({"answer": translated_answer})
        except requests.exceptions.RequestException as e:
            return jsonify({"error": str(e)}), 500
                
    else:
        # No translation needed
        try:
            response = ai_client.get_answers(question=user_question,
                                            project_name=ai_project_name,
                                            deployment_name=ai_deployment_name)
                    
            bot_response = response.answers[0].answer if response.answers else "No response from bot"
            return jsonify({"answer": bot_response})
        except requests.exceptions.RequestException as e:
            return jsonify({"error": str(e)}), 500


def detect_language(question):
    # Detects the language of the input text.
    path = '/detect?api-version=3.0'
    url = f"{translator_endpoint}{path}"
    headers = {
        'Ocp-Apim-Subscription-Key': translator_key,
        'Ocp-Apim-Subscription-Region': translator_region,
        'Content-type': 'application/json'
    }
    body = [{'text': question}]
    
    response = requests.post(url, headers=headers, json=body)
    response.raise_for_status()
    detected_language = response.json()[0]['language']
    return detected_language

def translate_text(question, target_language):
    #Translates the text into the target language.
   
    path = '/translate'
    url = f"{translator_endpoint}{path}"
    headers = {
        'Ocp-Apim-Subscription-Key': translator_key,
        'Ocp-Apim-Subscription-Region': translator_region,
        'Content-type': 'application/json'
    }
    params = {'api-version': '3.0', 'to': target_language}
    body = [{'text': question}]
    
    response = requests.post(url, headers=headers, params=params, json=body)
    response.raise_for_status()
    translated_text = response.json()[0]['translations'][0]['text']
    return translated_text

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