Spaces:
Running
Running
File size: 36,403 Bytes
829f2ca |
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 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 |
import os
import pickle
import time
from flask import Flask, render_template, request, jsonify, Response,session, send_file
from googletrans import Translator
from location import LocationExtractor
from date_extractor import extract_date
from map_visualizer import MapVisualizer
import pandas as pd
import ee
import speech_recognition as sr
from gtts import gTTS
from flask_cors import CORS
from google.transliteration import transliterate_word
import json
from gtts import gTTS
from geopy.distance import geodesic
from shapely.geometry import shape, Point
from flask import Flask, send_from_directory
from dotenv import load_dotenv
from groq import Groq
from reservoir import reservoirinfo
import threading
from gesture_detection import GestureControl
import cv2
import keyboard
from sign_language import SignLanguageRecognition
import numpy as np
import face_recognition
from PIL import Image
from keras.models import load_model
import google.generativeai as genai
from langchain_google_genai import ChatGoogleGenerativeAI
from langchain.prompts import PromptTemplate
from langchain.chains import LLMChain
import subprocess
from dotenv import load_dotenv
from groq import Groq
from io import BytesIO
from gtts import gTTS
from langchain.chains import ConversationChain, LLMChain
from langchain_core.prompts import (
ChatPromptTemplate,
HumanMessagePromptTemplate,
MessagesPlaceholder,
)
from langchain_core.messages import SystemMessage
from langchain.chains.conversation.memory import ConversationBufferWindowMemory
from langchain_groq import ChatGroq
import logging
service_account = 'isronrsc@isro-407105.iam.gserviceaccount.com'
credentials = ee.ServiceAccountCredentials(service_account, 'isro-407105-31fe627b6f09.json')
ee.Initialize(credentials)
app = Flask(__name__, static_folder='static')
CORS(app)
csv_file_path = 'ISROP.csv'
df = pd.read_csv(csv_file_path)
asset_ids = df['ROI_path'].tolist()
map_visualizer = MapVisualizer()
translator = Translator()
audio_text = ""
error = ""
browser_opened = False
gesture_control = GestureControl()
sign_language_recognition = SignLanguageRecognition()
cam = None
webcam_thread = None
with open('static/data/displaytext.json', 'r', encoding='utf-8') as file:
displayText = json.load(file)
dataset_path = "static/data/dataset"
face_detector = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
model1 = load_model('mobile_net_v2_firstmodel.h5')
max_emotion = None
max_count = 0
load_dotenv()
# Load the trained face recognition model
with open('static/data/dataset/trained_faces.pkl', 'rb') as f:
known_face_encodings, known_face_names = pickle.load(f)
def text_to_speech(text, lang, dest):
speech = gTTS(text=text, lang=lang)
speech.save(dest)
# Function to recognize faces
def recognize_face_encoding(unknown_encoding, known_face_encodings, tolerance=0.12):
name = ""
min_distance = float('inf')
for idx, known_encoding in enumerate(known_face_encodings):
distance = face_recognition.face_distance([known_encoding], unknown_encoding)
flat_distance = distance.flatten()
print(np.max(flat_distance), known_face_names[idx], min_distance)
if np.max(flat_distance) < min_distance:
min_distance = np.max(flat_distance)
name = known_face_names[idx]
if min_distance <= tolerance:
return name
@app.route('/qr', methods=['GET', 'POST'])
def qrscan():
if request.method == 'POST':
data = request.get_json()['data']
timestamp = str(int(time.time()))
qroutput_file_path = f"static/audio/qroutput/qroutput_{timestamp}.mp3"
text_to_speech(data, "en", qroutput_file_path)
return jsonify({'qroutput_file_path': qroutput_file_path})
return render_template('qr.html')
def predict_emotion(face_image):
face_image = cv2.imdecode(np.frombuffer(face_image, np.uint8), cv2.IMREAD_COLOR)
final_image = cv2.resize(face_image, (224, 224))
final_image = np.expand_dims(final_image, axis=0)
final_image = final_image / 255.0
predictions = model1.predict(final_image)
emotion_labels = ["Angry", "Disgust", "Fear", "Happy", "Surprise", "Sad", "Neutral"]
predicted_emotion = emotion_labels[np.argmax(predictions)]
return predicted_emotion
def initialize_bot(current_mood):
api_key = os.getenv('GENAI_API_KEY')
genai.configure(api_key = api_key)
title_template = PromptTemplate(input_variables = ['topic'], template = '')
if current_mood == 'Happy' or current_mood=='Surprise':
title_template = PromptTemplate(
input_variables = ['topic',],
template = 'You are Kriti, an intelligent and helpful AI chatbot created by NRSC ISRO, designed by dedicated student groups. You are tasked to answer any and all user queries. Greet the user and introduce yourself. The user looks happy from their expressions, set your tone accordingly and compliment them. This is their query{topic}'
)
elif current_mood == 'Sad' or current_mood == 'Fear':
title_template = PromptTemplate(
input_variables = ['topic'],
template = 'You are Kriti, an intelligent and helpful AI chatbot created by NRSC ISRO, designed by dedicated student groups. You are tasked to answer any and all user queries. Greet the user and introduce yourself. The user looks sad from their expressions, comfort them and ask them a bit about it and set your tone accordingly. This is their query {topic}'
)
elif current_mood == 'Angry' or current_mood == 'Disgust':
title_template = PromptTemplate(
input_variables = ['topic'],
template = 'You are Kriti, an intelligent and helpful AI chatbot created by NRSC ISRO, designed by dedicated student groups. You are tasked to answer any and all user queries. Greet the user and introduce yourself. The user looks irritated and unhappy from their expressions, Set your tone accordingly. This is their query {topic}'
)
elif current_mood == 'Neutral':
title_template = PromptTemplate(
input_variables = ['topic'],
template = 'You are Kriti, an intelligent and helpful AI chatbot created by NRSC ISRO, designed by dedicated student groups. You are tasked to answer any and all user queries. Greet the user in a human-ly manner. This is their query {topic}'
)
llm = ChatGoogleGenerativeAI(model = 'gemini-pro',google_api_key = api_key, temperature=0.5)
answer_chain = LLMChain(llm = llm, prompt = title_template, verbose = False)
return answer_chain
def bot_answer(question,current_mood):
answer_chain = initialize_bot(current_mood)
bot_response = answer_chain.run(topic = question, current_mood = current_mood)
return bot_response
def generate_video():
global webcam_displaying
video_capture = cv2.VideoCapture("http://127.0.0.1:8000/")
while webcam_displaying:
ret, frame = video_capture.read()
if not ret:
break
_, buffer = cv2.imencode('.jpg', frame)
frame = buffer.tobytes()
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')
video_capture.release()
@app.route('/video_feed')
def video_feed():
global webcam_displaying
webcam_displaying = True
return Response(generate_video(), mimetype='multipart/x-mixed-replace; boundary=frame')
@app.route('/recognize', methods=['GET'])
def recognize_face():
global detect_face, webcam_displaying, known_face_encodings, known_face_names, max_count, max_emotion
face_images = []
capture_interval = 1
start_time = time.time()
detect_face = "Welcome! "
# Capture video from webcam
video_capture = cv2.VideoCapture("http://127.0.0.1:8000/", cv2.CAP_DSHOW)
while webcam_displaying:
ret, frame = video_capture.read()
if ret:
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = face_detector.detectMultiScale(gray, 1.1, 4)
if len(faces) > 0:
largest_face = max(faces, key=lambda rect: rect[2] * rect[3])
x, y, w, h = largest_face
def expand_roi(x, y, w, h, scale_w, scale_h, img_shape):
new_x = max(int(x - w * (scale_w - 1) / 2), 0)
new_y = max(int(y - h * (scale_h - 1) / 2), 0)
new_w = min(int(w * scale_w), img_shape[1] - new_x)
new_h = min(int(h * scale_h), img_shape[0] - new_y)
return new_x, new_y, new_w, new_h
scale_w = 1.3
scale_h = 1.5
new_x, new_y, new_w, new_h = expand_roi(x, y, w, h, scale_w, scale_h, frame.shape)
roi_color = frame[new_y:new_y+new_h, new_x:new_x+new_w]
if time.time() - start_time >= capture_interval:
face_images.append(cv2.imencode('.png', roi_color)[1].tobytes())
if len(face_images) > 5:
face_images.pop(0)
start_time = time.time()
emotion_counts = {"Angry": 0, "Disgust": 0, "Fear": 0, "Happy": 0, "Surprise": 0, "Sad": 0, "Neutral": 0}
if len(face_images) >= 4:
for face_image in face_images:
predicted_emotion = predict_emotion(face_image)
emotion_counts[predicted_emotion] += 1
max_emotion = max(emotion_counts, key=emotion_counts.get)
max_count = emotion_counts[max_emotion]
if detect_face == "Welcome! ":
rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
# Detect faces in the frame
face_locations = face_recognition.face_locations(rgb_frame)
face_encodings = face_recognition.face_encodings(rgb_frame, face_locations)
copy_frame = frame.copy()
for face_encoding, face_location in zip(face_encodings, face_locations):
print(face_location)
name = recognize_face_encoding(face_encoding, known_face_encodings)
if name:
if detect_face == "Welcome! ":
detect_face += name
else:
detect_face += ", " + name
top, right, bottom, left = face_location
cv2.rectangle(copy_frame, (left, top), (right, bottom), (0, 255, 0), 2)
cv2.putText(copy_frame, name, (left + 6, bottom - 6), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 255, 0), 2)
cv2.imwrite("static/assets/display.png", copy_frame)
if len(face_images) >= 4:
webcam_displaying = False
video_capture.release()
if len(detect_face.split(',')) > 1:
detect_face = detect_face[0:detect_face.rfind(',')] + " and " + detect_face[detect_face.rfind(',')+1:]
print("Max emotion: ", max_emotion)
query = 'Who are you?'
response = bot_answer(query,max_emotion)
if max_emotion not in ["Happy","Sad","Neutral","Angry",""]:
max_emotion = "Neutral"
timestamp = str(int(time.time()))
reconize_file_path = f"static/audio/recognize/recognize_{timestamp}.mp3"
text_to_speech(detect_face + response, "en", reconize_file_path)
return jsonify({'names': detect_face, 'image': "static/assets/display.png", 'reconize_file_path': reconize_file_path, 'emotion': max_emotion, 'response': response})
@app.route('/command', methods=['GET', 'POST'])
def handle_command():
global detect_face, max_count, max_emotion
detect_face = ""
max_count = 0
max_emotion = None
return render_template('command.html')
# API endpoint URL
# url = 'http://mt-ulca-api.rb-aai.in/getbulksyncULCA'
# # Request payload
# payload = {
# "input": [
# {
# "source": text
# }
# ],
# "config": {
# "language": {
# "sourceLanguage": "en",
# "targetLanguage": "hi"
# }
# }
# }
# response = requests.post(url, json=payload)
# # Check the response
# if response.status_code == 200:
# return response.json()['output'][0]['target']
# else:
# print(f'Error: {response.status_code}, {response.text}')
def convert_text_to_text(text, s_lang, d_lang):
numeral_mappings = {
# Telugu numerals
'౧': '1', '౨': '2', '౩': '3', '౪': '4', '౫': '5',
'౬': '6', '౭': '7', '౮': '8', '౯': '9', '౦': '0',
# Tamil numerals
'௧': '1', '௨': '2', '௩': '3', '௪': '4', '௫': '5',
'௬': '6', '௭': '7', '௮': '8', '௯': '9', '௦': '0',
# Malayalam numerals
'൧': '1', '൨': '2', '൩': '3', '൪': '4', '൫': '5',
'൬': '6', '൭': '7', '൮': '8', '൯': '9', '൦': '0',
# Gujarati numerals
'૧': '1', '૨': '2', '૩': '3', '૪': '4', '૫': '5',
'૬': '6', '૭': '7', '૮': '8', '૯': '9', '૦': '0',
# Bengali numerals
'১': '1', '২': '2', '৩': '3', '৪': '4', '৫': '5',
'৬': '6', '৭': '7', '৮': '8', '৯': '9', '০': '0',
# Kannada numerals
'೧': '1', '೨': '2', '೩': '3', '೪': '4', '೫': '5',
'೬': '6', '೭': '7', '೮': '8', '೯': '9', '೦': '0',
}
for numeral, replacement in numeral_mappings.items():
text = text.replace(numeral, replacement)
return translator.translate(text=text, src=s_lang, dest=d_lang).text
def text_to_speech(text, lang, dest):
speech = gTTS(text=text, lang=lang)
speech.save(dest)
@app.route('/transliterate', methods=['POST'])
def transliterate():
text_to_transliterate = request.get_json()['text']
lang_code = displayText[request.get_json()['lang']]['code']
if text_to_transliterate:
suggestions = transliterate_word(text_to_transliterate, lang_code=lang_code)
return jsonify({'translation': suggestions})
return jsonify({'translation': []})
@app.route('/', methods=['GET', 'POST'])
def index():
global audio_text
directories = ['static/assets/plot', 'static/audio/command', 'static/audio/qroutput', 'static/audio/recognize', 'static/audio/status', 'static/audio/conclusion']
for directory in directories:
for filename in os.listdir(directory):
if (filename.startswith('doyoumean') or filename.startswith('conclusion') or filename.startswith('status') or filename.startswith('qroutput') or filename.startswith('recognize') or filename.startswith('chart')):
file_path = os.path.join(directory, filename)
os.remove(file_path)
if request.method == 'POST':
try:
lang = request.form['lang']
if lang == "english":
if audio_text == "":
user_text = request.form['user_text']
else:
user_text = audio_text
if user_text != "":
user_text = request.form['user_text']
print(user_text)
location_extractor = LocationExtractor()
selected_roi_name, exact = location_extractor.extract_entities(input_text=user_text)
if exact != "exact":
timestamp = str(int(time.time()))
audio_file_path = f"static/audio/doyoumean/doyoumean_{timestamp}.mp3"
text_to_speech(displayText[lang]['dym'] + selected_roi_name, "en", audio_file_path)
while not os.path.exists(audio_file_path):
time.sleep(0.1)
return jsonify({'selection': displayText[lang]['dym'] + selected_roi_name,
'selected_roi_name': selected_roi_name,
'user_text': user_text,
'audio_file_path': audio_file_path
});
return jsonify({
'selected_roi_name': selected_roi_name,
'user_text': user_text,
});
if audio_text == "" and user_text == "":
return jsonify({'status': displayText[lang]['inputIssue']})
return jsonify({'status': displayText[lang]['error']})
else:
if audio_text == "":
user_text = convert_text_to_text(request.form['user_text'], displayText[lang]['code'], "en")
else:
user_text = convert_text_to_text(audio_text, displayText[lang]['code'], "en")
if user_text != "":
user_text = convert_text_to_text(request.form['user_text'], displayText[lang]['code'], "en")
print(user_text)
location_extractor = LocationExtractor()
selected_roi_name, exact = location_extractor.extract_entities(input_text=user_text)
if exact != "exact":
timestamp = str(int(time.time()))
audio_file_path = f"static/audio/doyoumean/doyoumean_{timestamp}.mp3"
converted_roi_name = convert_text_to_text(selected_roi_name, 'en', displayText[lang]['code'])
text_to_speech(displayText[lang]['dym'] + converted_roi_name, displayText[lang]['code'], audio_file_path)
while not os.path.exists(audio_file_path):
time.sleep(0.1)
return jsonify({'selection': displayText[lang]['dym'] + converted_roi_name,
'selected_roi_name': selected_roi_name,
'user_text': user_text,
'audio_file_path': audio_file_path
});
return jsonify({
'selected_roi_name': selected_roi_name,
'user_text': user_text,
});
if audio_text == "" and user_text == "":
return jsonify({'status': displayText[lang]['inputIssue']})
return jsonify({'status': displayText[lang]['error']})
except Exception as e:
return jsonify({'status': 'Exception found', 'message': str(e)})
# For GET requests, render the template without map_html and conclusion
return render_template('index.html')
@app.route('/date', methods=['POST'])
def date_gatherer():
global audio_text
lang = request.get_json()['lang']
user_text = request.get_json()['user_text']
start_date, end_date = extract_date(convert_text_to_text(user_text, displayText[lang]['code'], "en"))
audio_text = ""
text_to_speech(displayText[lang]['query'] + user_text + ".", displayText[lang]['code'], "static/audio/languages/" + lang + "/step2.mp3")
return jsonify({
'start_date': start_date,
'end_date': end_date
})
@app.route('/map', methods=['POST'])
def map__reservior():
global audio_text
lang = request.get_json()['lang']
start_date, end_date, selected_roi_name = request.get_json()['start_date'], request.get_json()['end_date'], request.get_json()['selected_roi_name']
# Run the analysis in the background
static_map, conclusion, chart_file_path, status, maperror = map_visualizer.run_analysis(
asset_ids, selected_roi_name, start_date, end_date, csv_file_path, lang
)
audio_text = ""
# file_name = 'static_map.html'
# # Write the HTML content to the file
# with open(file_name, 'w') as file:
# file.write(static_map.to_html())
# print(f"HTML file '{file_name}' has been created.")
if status == "" and maperror == "":
return jsonify({
'map_html': static_map,
'conclusion': conclusion,
'conclusion_file_path': "",
'chart_file_path': chart_file_path,
'status': status,
'error': displayText[lang]['reservoirIssue']
})
if static_map != None:
# Convert Earth Engine map to HTML code
map_html = static_map.to_html()
converted_conclusion = ""
timestamp = str(int(time.time()))
conclusion_file_path = f"static/audio/conclusion/conclusion_{timestamp}.mp3"
if lang == "english":
converted_conclusion = conclusion
text_to_speech(conclusion, 'en', conclusion_file_path)
else:
for con in conclusion.split(". "):
converted_conclusion += convert_text_to_text(con, "en", displayText[lang]['code']) + ". "
text_to_speech(converted_conclusion, displayText[lang]['code'], conclusion_file_path)
return jsonify({
'map_html': map_html,
'conclusion': converted_conclusion,
'conclusion_file_path': conclusion_file_path,
'chart_file_path': chart_file_path,
'status': status,
'error': maperror
})
else:
converted_status = ""
timestamp = str(int(time.time()))
status_file_path = f"static/audio/status/status_{timestamp}.mp3"
if lang == "english":
converted_status = status
text_to_speech(status, 'en', status_file_path)
else:
for con in status.split(". "):
converted_status += convert_text_to_text(con, "en", displayText[lang]['code']) + ". "
text_to_speech(converted_status, displayText[lang]['code'], status_file_path)
return jsonify({
'map_html': static_map,
'conclusion': conclusion,
'conclusion_file_path': status_file_path,
'chart_file_path': chart_file_path,
'status': converted_status,
'error': maperror
})
@app.route('/timelapse', methods=['POST'])
def timelapse():
selected_roi_name = request.get_json()['selected_roi_name']
total_chunks, video_thumb_url, num_chunk = map_visualizer.timelapse(
asset_ids, selected_roi_name
)
return jsonify({
"total_chunks": total_chunks,
"video_thumb_url": video_thumb_url,
"num_chunk": num_chunk
})
@app.route('/process', methods=['POST'])
def processchunk():
total_chunks, num_chunk = request.get_json()['total_chunks'], request.get_json()['num_chunk']
total_chunks, video_thumb_url, num_chunk = map_visualizer.process_each_chunk(
total_chunks, num_chunk
)
return jsonify({
"video_thumb_url": video_thumb_url,
"num_chunk": num_chunk
})
@app.route('/about', methods=['GET'])
def about():
return render_template('about.html')
@app.route('/info', methods=['GET'])
def info():
return render_template('info.html')
@app.route('/reservoirs', methods=['POST'])
def reservoirs():
return reservoirinfo(request.get_json()['type'])
@app.route('/startstop', methods=['POST'])
def startstop():
lang = request.get_json()['lang']
type_audio = request.get_json()['type_audio']
global audio_text
global error
recognizer = sr.Recognizer()
audio_text = ""
error = ""
user_ended = True
if type_audio == "start":
user_ended = False
else:
user_ended = True
stop = False
while not stop and not user_ended:
with sr.Microphone() as source:
recognizer.adjust_for_ambient_noise(source) # Adjust for ambient noise
try:
audio = recognizer.listen(source)
print("Recognizing...")
audio_text = recognizer.recognize_google(audio, language=displayText[lang]['audioCode'])
print("You said:", audio_text)
if audio_text != "" or user_ended:
stop = True
except sr.UnknownValueError:
print("Could not understand audio")
error = displayText[lang]['audioIssue']
stop = True
except sr.RequestError as e:
print(f"Could not request results from API {e}")
error = displayText[lang]['apiIssue']
stop = True
except sr.WaitTimeoutError:
print("Microphone timeout. Stopping...")
return jsonify({'message': audio_text, "error": error})
@app.route('/start_webcam', methods=['GET'])
def api_start_webcam():
global cam, webcam_thread
# Start webcam
cam = cv2.VideoCapture(0)
gesture_control.set_webcam(cam)
# Start the gesture control in a separate thread
webcam_thread = threading.Thread(target=gesture_control.start)
webcam_thread.start()
print("Webcam started")
return jsonify("Webcam started successfully")
@app.route('/stop_webcam', methods=['GET'])
def api_stop_webcam():
global cam, webcam_thread
# Stop both recognition processes
gesture_control.stop()
sign_language_recognition.stop()
# Join the webcam thread if it is alive
if webcam_thread is not None and webcam_thread.is_alive():
webcam_thread.join()
# Release the webcam
if cam is not None:
cam.release()
cam = None
print("Webcam stopped")
return jsonify("Webcam stopped successfully")
@app.route('/start_sign', methods=['GET'])
def api_start_sign():
global cam, webcam_thread
# Stop gesture control if it is running
gesture_control.stop()
cam = cv2.VideoCapture(0)
sign_language_recognition.set_webcam(cam)
# Start sign language recognition in a separate thread
webcam_thread = threading.Thread(target=sign_language_recognition.start)
webcam_thread.start()
print("Sign language recognition started")
return jsonify("Sign started successfully")
@app.route('/stop_sign', methods=['GET'])
def api_stop_sign():
global cam, webcam_thread
# Stop the sign language recognition process
sign_language_recognition.stop()
# Restart gesture control
cam = cv2.VideoCapture(0)
gesture_control.set_webcam(cam)
webcam_thread = threading.Thread(target=gesture_control.start)
webcam_thread.start()
print("Sign language recognition stopped")
return jsonify("Sign stopped successfully")
@app.route('/typed_text', methods=['GET'])
def get_typed_text():
global sign_language_recognition
return jsonify({"typed_text": sign_language_recognition.typed_text})
# Load reservoir data
reservoirs = pd.read_csv('ISROP.csv') # Ensure this CSV file is correctly formatted
# Function to find the nearest reservoir within 10 km
def find_nearest_reservoir(lat, lon):
min_distance = float('inf')
nearest_reservoir = None
for index, row in reservoirs.iterrows():
reservoir_location = (row['Latitude'], row['Longitude']) # Ensure these column names match your CSV
distance = geodesic((lat, lon), reservoir_location).km
if distance < 10 and distance < min_distance: # Limit search within 10 km radius
min_distance = distance
nearest_reservoir = row
return nearest_reservoir
# Function to calculate a buffer around a reservoir boundary
def calculate_buffer(roi_name):
# Get the Earth Engine asset path for the reservoir based on roi_name
asset_id = f'projects/isro-407105/assets/{roi_name}'
try:
ee_shapefile = ee.FeatureCollection(asset_id)
# Buffer distance in meters (10 km = 10000 meters)
buffered_shapefile = ee_shapefile.geometry().buffer(10000)
return buffered_shapefile
except Exception as e:
print(f"Error calculating buffer for {roi_name}: {e}")
return None
# Function to get the GeoJSON of the reservoir shapefile from Google Earth Engine
def get_reservoir_geojson(roi_name):
# Get the Earth Engine asset path for the reservoir based on roi_name
asset_id = f'projects/isro-407105/assets/{roi_name}'
try:
ee_shapefile = ee.FeatureCollection(asset_id)
geojson = ee_shapefile.getInfo()
return geojson
except Exception as e:
print(f"Error fetching GeoJSON for {roi_name}: {e}")
return None
# # Route to serve reservoir.html
@app.route('/reservoir')
def reservoir():
return render_template('reservoir.html')
# return send_from_directory('templates', 'reservoir.html')
# Route to find nearest reservoir
@app.route('/find_nearest_reservoir', methods=['POST'])
def find_nearest_reservoir_endpoint():
request_data = request.get_json()
lat = float(request_data['lat'])
lon = float(request_data['lon'])
# Calculate buffers and find the nearest reservoir
nearest_reservoir = None
min_distance = float('inf')
for index, row in reservoirs.iterrows():
reservoir_location = (row['Latitude'], row['Longitude']) # Ensure these column names match your CSV
distance = geodesic((lat, lon), reservoir_location).km
# Calculate buffer for the reservoir
buffered_shapefile = calculate_buffer(row['ROI_Name'])
if buffered_shapefile is not None:
# Check if the click point is within the buffered area
if buffered_shapefile.contains(ee.Geometry.Point(lon, lat)):
# Update nearest reservoir if closer
if distance < min_distance:
min_distance = distance
nearest_reservoir = row
if nearest_reservoir is not None:
geojson = get_reservoir_geojson(nearest_reservoir['ROI_Name'])
if geojson:
return jsonify({
'name': nearest_reservoir['ROI_Name'],
'state': nearest_reservoir['State'],
'latitude': nearest_reservoir['Latitude'],
'longitude': nearest_reservoir['Longitude'],
'color': nearest_reservoir['Color'],
'geojson': geojson, # Return the GeoJSON data
'distance': min_distance
})
else:
return jsonify({
'name': nearest_reservoir['ROI_Name'],
'state': nearest_reservoir['State'],
'latitude': nearest_reservoir['Latitude'],
'longitude': nearest_reservoir['Longitude'],
'color': nearest_reservoir['Color'],
'error': f"Shapefile for {nearest_reservoir['ROI_Name']} not found in Earth Engine."
})
else:
return jsonify({'error': 'No reservoir found within 10 km.'})
# Route to handle chat query
@app.route('/search')
def search():
query = request.args.get('query', '')
# Render the chat page or handle the query as needed
return render_template('index.html', query=query)
client = Groq()
data = {}
#@app.route('/voice_assistant')
#def voice_assistant():
# return render_template('voice_assistant.html')
@app.route('/chat', methods=['POST'])
def chat():
user_input = request.json.get('message')
target_language = request.json.get('language')
try:
response_text = process_query(user_input)
if not response_text:
chat_completion = client.chat.completions.create(
messages=[
{
"role": "user",
"content": user_input,
}
],
model="gemma2-9b-it",
)
response_text = chat_completion.choices[0].message.content
if not response_text.strip():
response_text = "Sorry, I don't have a response for that."
if target_language != 'en':
translation = translate_text(response_text, target_language)
response_text = translation
return jsonify({'response': response_text})
except Exception as e:
return jsonify({'error': str(e)}), 500
def process_query(input_text):
max_query_length = 500
responses = []
while input_text:
query_chunk = input_text[:max_query_length]
input_text = input_text[max_query_length:]
chat_completion = client.chat.completions.create(
messages=[{"role": "user", "content": query_chunk}],
model="gemma2-9b-it"
)
response_text = chat_completion.choices[0].message.content
responses.append(response_text)
return ' '.join(responses)
def translate_text(text, target_language):
return text
app.secret_key = 'supersecretkey' # Needed for session management
# Define the Groq API key
groq_api_key = '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' # Replace with your actual API key
# Initialize Groq Langchain chat object and conversation memory
model = 'llama-3.3-70b-versatile'
conversational_memory_length = 5
memory = ConversationBufferWindowMemory(k=conversational_memory_length, memory_key="chat_history", return_messages=True)
system_prompt = """
You are Kriti, an intelligent and helpful AI chatbot created by ISRO, designed by dedicated student groups. Provide accurate, concise, and helpful information in brief responses. Only refer to your identity when explicitly asked.
"""
@app.route("/voiceassistant", methods=["GET", "POST"])
def va():
if request.method == "POST":
user_input = request.get_json().get("question")
if user_input:
if 'chat_history' not in session:
session['chat_history'] = []
for message in session.get("chat_history", []):
memory.save_context(
{"input": message["human"]},
{"output": message["AI"]}
)
groq_chat = ChatGroq(groq_api_key=groq_api_key, model_name=model)
prompt = ChatPromptTemplate.from_messages(
[
SystemMessage(content=system_prompt),
MessagesPlaceholder(variable_name="chat_history"),
HumanMessagePromptTemplate.from_template("{human_input}"),
]
)
conversation = LLMChain(
llm=groq_chat,
prompt=prompt,
verbose=True,
memory=memory,
)
response = conversation.predict(human_input=user_input)
message = {"human": user_input, "AI": response}
session["chat_history"].append(message)
return jsonify({"response": response})
# For GET requests, render the HTML template
return render_template("voiceassistant.html", chat_history=session.get("chat_history", []))
@app.route("/voiceassistant/audio")
def audio():
response = request.args.get("response", "")
tts = gTTS(text=response, lang='en')
audio = BytesIO()
tts.write_to_fp(audio)
audio.seek(0)
return send_file(audio, mimetype="audio/mp3")
if __name__ == '__main__':
app.run(debug=True)
|