wookimchye commited on
Commit
d25f863
·
verified ·
1 Parent(s): 94ca821

Upload 5 files

Browse files
Files changed (5) hide show
  1. .env +7 -0
  2. Dockerfile +17 -0
  3. Web-Chatbot-Multilingual-app.py +111 -0
  4. requirements.txt +6 -0
  5. templates/index.html +135 -0
.env ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ AI_SERVICE_ENDPOINT=https://iti109-sectionb.cognitiveservices.azure.com/
2
+ AI_SERVICE_KEY=2ou0CMAjUutj0D4In8U8AkxEIXtCrvYFOBMhqSW4rZ7x6yZ033GdJQQJ99ALACqBBLyXJ3w3AAAaACOGtVJj
3
+ QA_PROJECT_NAME=ITI109-SectionB-FAQ
4
+ QA_DEPLOYMENT_NAME=production
5
+ TRANSLATOR_KEY=25ooP3rvvZbd9FhLzc4NEzV5vKhDrXa7n2hYGDfBel2zQQDdJh9TJQQJ99ALACqBBLyXJ3w3AAAbACOGtt5Z
6
+ TRANSLATOR_ENDPOINT=https://api.cognitive.microsofttranslator.com/
7
+ TRANSLATOR_REGION=southeastasia
Dockerfile ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Use an official Python runtime as the base image
2
+ FROM python:3.9
3
+
4
+ # Set the working directory in the container
5
+ WORKDIR /app
6
+
7
+ # Copy all project files to the container
8
+ COPY . /app
9
+
10
+ # Install dependencies
11
+ RUN pip install --no-cache-dir -r requirements.txt
12
+
13
+ # Expose the port Flask will run on
14
+ EXPOSE 7860
15
+
16
+ # Command to start the application
17
+ CMD ["gunicorn", "--bind", "0.0.0.0:7860", "Web-Chatbot-app:app"]
Web-Chatbot-Multilingual-app.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask import Flask, render_template, request, jsonify
2
+ import requests
3
+ from dotenv import load_dotenv
4
+ import os
5
+ import json
6
+
7
+ # import namespaces
8
+ from azure.core.credentials import AzureKeyCredential
9
+ from azure.ai.language.questionanswering import QuestionAnsweringClient
10
+
11
+ from azure.ai.translation.text import *
12
+ from azure.ai.translation.text.models import InputTextItem
13
+
14
+ app = Flask(__name__)
15
+
16
+ # Get Configuration Settings
17
+ load_dotenv()
18
+ # Settings for QnA
19
+ ai_endpoint = os.getenv('AI_SERVICE_ENDPOINT')
20
+ ai_key = os.getenv('AI_SERVICE_KEY')
21
+ ai_project_name = os.getenv('QA_PROJECT_NAME')
22
+ ai_deployment_name = os.getenv('QA_DEPLOYMENT_NAME')
23
+ # SEttings for Translator
24
+ translator_endpoint = os.getenv('TRANSLATOR_ENDPOINT')
25
+ translator_region = os.getenv('TRANSLATOR_REGION')
26
+ translator_key = os.getenv('TRANSLATOR_KEY')
27
+
28
+ # Create client using endpoint and key
29
+ credential = AzureKeyCredential(ai_key)
30
+ ai_client = QuestionAnsweringClient(endpoint=ai_endpoint, credential=credential)
31
+
32
+ @app.route('/')
33
+ def home():
34
+ return render_template('index.html') # HTML file for the web interface
35
+
36
+ @app.route('/ask', methods=['POST'])
37
+ def ask_bot():
38
+ user_question = request.json.get("question", "")
39
+
40
+ if not user_question:
41
+ return jsonify({"error": "No question provided"}), 400
42
+
43
+ # Detect the language of the input text
44
+ detected_language = detect_language(user_question)
45
+
46
+ # If the detected language is not English, translate the question to English; else continue to get the answer
47
+ if detected_language != 'en':
48
+ # Translate the question into English
49
+ translated_question = translate_text(user_question, 'en')
50
+ try:
51
+ response = ai_client.get_answers(question=translated_question,
52
+ project_name=ai_project_name,
53
+ deployment_name=ai_deployment_name)
54
+
55
+ bot_response = response.answers[0].answer if response.answers else "No response from bot"
56
+
57
+ # Translate the answer back to the original language
58
+ translated_answer = translate_text(response.answers[0].answer, detected_language)
59
+ return jsonify({"answer": translated_answer})
60
+ except requests.exceptions.RequestException as e:
61
+ return jsonify({"error": str(e)}), 500
62
+
63
+ else:
64
+ # No translation needed
65
+ try:
66
+ response = ai_client.get_answers(question=user_question,
67
+ project_name=ai_project_name,
68
+ deployment_name=ai_deployment_name)
69
+
70
+ bot_response = response.answers[0].answer if response.answers else "No response from bot"
71
+ return jsonify({"answer": bot_response})
72
+ except requests.exceptions.RequestException as e:
73
+ return jsonify({"error": str(e)}), 500
74
+
75
+
76
+ def detect_language(question):
77
+ # Detects the language of the input text.
78
+ path = '/detect?api-version=3.0'
79
+ url = f"{translator_endpoint}{path}"
80
+ headers = {
81
+ 'Ocp-Apim-Subscription-Key': translator_key,
82
+ 'Ocp-Apim-Subscription-Region': translator_region,
83
+ 'Content-type': 'application/json'
84
+ }
85
+ body = [{'text': question}]
86
+
87
+ response = requests.post(url, headers=headers, json=body)
88
+ response.raise_for_status()
89
+ detected_language = response.json()[0]['language']
90
+ return detected_language
91
+
92
+ def translate_text(question, target_language):
93
+ #Translates the text into the target language.
94
+
95
+ path = '/translate'
96
+ url = f"{translator_endpoint}{path}"
97
+ headers = {
98
+ 'Ocp-Apim-Subscription-Key': translator_key,
99
+ 'Ocp-Apim-Subscription-Region': translator_region,
100
+ 'Content-type': 'application/json'
101
+ }
102
+ params = {'api-version': '3.0', 'to': target_language}
103
+ body = [{'text': question}]
104
+
105
+ response = requests.post(url, headers=headers, params=params, json=body)
106
+ response.raise_for_status()
107
+ translated_text = response.json()[0]['translations'][0]['text']
108
+ return translated_text
109
+
110
+ if __name__ == '__main__':
111
+ app.run(debug=True)
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ Flask
2
+ requests
3
+ azure-ai-language-questionanswering
4
+ azure-core
5
+ python-dotenv
6
+ gunicorn
templates/index.html ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>Asian Food Chatbot</title>
7
+ <style>
8
+ body {
9
+ font-family: Arial, sans-serif;
10
+ background-color: #f4f4f9;
11
+ margin: 0;
12
+ padding: 0;
13
+ display: flex;
14
+ justify-content: center;
15
+ align-items: center;
16
+ height: 100vh;
17
+ }
18
+ .chat-container {
19
+ width: 400px;
20
+ background-color: #fff;
21
+ box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
22
+ border-radius: 8px;
23
+ overflow: hidden;
24
+ display: flex;
25
+ flex-direction: column;
26
+ }
27
+ .chat-header {
28
+ background-color: #007bff;
29
+ color: #fff;
30
+ padding: 10px;
31
+ text-align: center;
32
+ font-size: 1.2em;
33
+ }
34
+ .chat-messages {
35
+ flex: 1;
36
+ padding: 10px;
37
+ overflow-y: auto;
38
+ }
39
+ .chat-input {
40
+ display: flex;
41
+ border-top: 1px solid #ddd;
42
+ }
43
+ .chat-input input {
44
+ flex: 1;
45
+ padding: 10px;
46
+ border: none;
47
+ border-radius: 0;
48
+ outline: none;
49
+ }
50
+ .chat-input button {
51
+ padding: 10px;
52
+ background-color: #007bff;
53
+ color: #fff;
54
+ border: none;
55
+ cursor: pointer;
56
+ }
57
+ .chat-input button:hover {
58
+ background-color: #0056b3;
59
+ }
60
+ .message {
61
+ margin-bottom: 10px;
62
+ }
63
+ .message.user {
64
+ text-align: right;
65
+ }
66
+ .message.bot {
67
+ text-align: left;
68
+ }
69
+ .message .text {
70
+ display: inline-block;
71
+ padding: 10px;
72
+ border-radius: 8px;
73
+ max-width: 70%;
74
+ }
75
+ .message.user .text {
76
+ background-color: #007bff;
77
+ color: #fff;
78
+ }
79
+ .message.bot .text {
80
+ background-color: #f1f1f1;
81
+ color: #333;
82
+ }
83
+ </style>
84
+ </head>
85
+ <body>
86
+ <div class="chat-container">
87
+ <div class="chat-header">Asian Food Chatbot</div>
88
+ <div class="chat-messages" id="chat-messages"></div>
89
+ <div class="chat-input">
90
+ <input type="text" id="user-input" placeholder="Type a message...">
91
+ <button onclick="sendMessage()">Send</button>
92
+ </div>
93
+ </div>
94
+
95
+ <script>
96
+ function sendMessage() {
97
+ const userInput = document.getElementById('user-input');
98
+ const message = userInput.value.trim();
99
+ if (message) {
100
+ addMessage('user', message);
101
+ userInput.value = '';
102
+
103
+ // Call the /ask endpoint of the Flask server
104
+ fetch('/ask', {
105
+ method: 'POST',
106
+ headers: {
107
+ 'Content-Type': 'application/json'
108
+ },
109
+ body: JSON.stringify({ question: message })
110
+ })
111
+ .then(response => response.json())
112
+ .then(data => {
113
+ addMessage('bot', data.answer);
114
+ })
115
+ .catch(error => {
116
+ console.error('Error:', error);
117
+ addMessage('bot', 'Error: Unable to retrieve answer');
118
+ });
119
+ }
120
+ }
121
+
122
+ function addMessage(sender, text) {
123
+ const chatMessages = document.getElementById('chat-messages');
124
+ const messageElement = document.createElement('div');
125
+ messageElement.classList.add('message', sender);
126
+ const textElement = document.createElement('div');
127
+ textElement.classList.add('text');
128
+ textElement.textContent = text;
129
+ messageElement.appendChild(textElement);
130
+ chatMessages.appendChild(messageElement);
131
+ chatMessages.scrollTop = chatMessages.scrollHeight;
132
+ }
133
+ </script>
134
+ </body>
135
+ </html>