Spaces:
Running
Running
| 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 | |
| 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() | |
| def video_feed(): | |
| global webcam_displaying | |
| webcam_displaying = True | |
| return Response(generate_video(), mimetype='multipart/x-mixed-replace; boundary=frame') | |
| 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}) | |
| 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) | |
| 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': []}) | |
| 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') | |
| 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 | |
| }) | |
| 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 | |
| }) | |
| 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 | |
| }) | |
| 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 | |
| }) | |
| def about(): | |
| return render_template('about.html') | |
| def info(): | |
| return render_template('info.html') | |
| def reservoirs(): | |
| return reservoirinfo(request.get_json()['type']) | |
| 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}) | |
| 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") | |
| 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") | |
| 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") | |
| 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") | |
| 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 | |
| def reservoir(): | |
| return render_template('reservoir.html') | |
| # return send_from_directory('templates', 'reservoir.html') | |
| # Route to find nearest reservoir | |
| 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 | |
| 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') | |
| 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. | |
| """ | |
| 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", [])) | |
| 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) | |