CoolFace
Apppublic

Shashikiran42/Multitasking-Chatbot

sourceHugging Faceupdated 2y agoView on Hugging Face
0likes
app.py275 linesDownload Raw Back to root
1from flask import Flask, render_template, request, jsonify2from huggingface_hub import InferenceClient3import requests4import folium5import polyline6import base647 8# =================================== Initializations =================================== #9# Initialize flask10app = Flask(__name__)11 12# Initialize the Hugging Face model13client = InferenceClient(model="mistralai/Mixtral-8x7B-Instruct-v0.1")14 15# Spotify Initializations16CLIENT_ID = 'f18d5f1bbc5c4f2bbdd24c33c8da38cf'17CLIENT_SECRET = 'bc0bc31a06cd48b0aed581869d7f86f2'18SPOTIFY_API_URL = 'https://api.spotify.com/v1/'19 20# Replace with your actual GraphHopper API key21GRAPHHOPPER_API_KEY = 'f70a4563-ed75-45cb-965c-7d92054db22c'22GRAPHHOPPER_URL = 'https://graphhopper.com/api/1/'23 24# Language based system prompts25english_system_prompt = "Please answer the questions as concisely and politely as possible. You are virtually located at Fairfield University Campus, in Fairfield, CT."26# english_system_prompt = "You are a helpful assistant, virtually located at Fairfield University Campus, in Fairfield, CT."27spanish_system_prompt = "Eres un útil asistente de IA. Por favor responda las preguntas de manera concisa y cortés. Está ubicado en el campus de la Universidad de Fairfield, en Fairfield, CT."28italian_system_prompt = "Sei un utile assistente AI. Si prega di rispondere alle domande in modo conciso e cortese. Ti trovi nel campus della Fairfield University, a Fairfield, CT."29french_system_prompt = "Vous êtes un assistant IA utile. Veuillez répondre aux questions de manière concise et polie. Vous êtes situé sur le campus de l'Université Fairfield, à Fairfield, CT."30german_system_prompt = "Sie sind ein hilfreicher KI-Assistent. Bitte beantworten Sie die Fragen prägnant und höflich. Sie befinden sich auf dem Fairfield University Campus in Fairfield, CT."31 32# Initialize conversation history33conversation_history = []34 35# =================================== Global Functions =================================== #36def geocode_location(api_key, location):37    # Geocode location using GraphHopper Geocoding API38    geocoding_url = f'https://graphhopper.com/api/1/geocode?q={location}&key={api_key}'39    response = requests.get(geocoding_url)40 41    if response.status_code == 200:42        data = response.json()43        # Extract the coordinates from the geocoding response44        coordinates = [data["hits"][0]["point"]["lat"], data["hits"][0]["point"]["lng"]]45        return coordinates46    else:47        print(f'Geocoding Error: {response.status_code}, {response.text}')48        return None49 50def get_mapping_access_token():51    auth_header = base64.b64encode((CLIENT_ID + ':' + CLIENT_SECRET).encode('utf-8')).decode('utf-8')52    headers = {'Authorization': 'Basic {}'.format(auth_header)}53    data = {54        'grant_type': 'client_credentials',55    }56    response = requests.post('https://accounts.spotify.com/api/token', data=data, headers=headers)57    if response.status_code == 200:58        token_info = response.json()59        access_token = token_info['access_token']60        return access_token61    else:62        return None63 64def format_prompt(message, history):65    prompt = "<s>"66    for user_prompt, bot_response in history:67        prompt += f"[INST] {user_prompt} [/INST]"68        prompt += f" {bot_response}</s> "69    prompt += f"[INST] {message} [/INST]"70    return prompt71 72def generate_output(prompt, history, system_prompt):73    formatted_prompt = format_prompt(f"{system_prompt}, {prompt}", history)74    generate_kwargs = dict(75        temperature=0.15,76        max_new_tokens=512,77        top_p=0.9,78        repetition_penalty=1.0,79        do_sample=True,80        seed=42,81    )82    output = client.text_generation(formatted_prompt, **generate_kwargs)83    return output84 85 86# =================================== Flask Routes =================================== #87@app.route('/')88def index():89    return render_template('index.html')90 91# Process Message Route - Normal Bot Response92@app.route('/process_message', methods=['POST'])93def process_message():94    user_input = request.json['message']95    selected_language = request.json['language']96    if selected_language == "english":97        system_prompt = english_system_prompt98    elif selected_language == "spanish":99        system_prompt = spanish_system_prompt100    elif selected_language == "french":101        system_prompt = french_system_prompt102    elif selected_language == "german":103        system_prompt = german_system_prompt104    elif selected_language == "italian":105        system_prompt = italian_system_prompt106    else:107        system_prompt = english_system_prompt108 109    bot_response = generate_output(user_input, conversation_history, system_prompt)110    conversation_history.append((user_input, bot_response))111    return jsonify({'response': bot_response})112 113# Clear Conversation History Route114@app.route('/clear_history', methods=['POST'])115def clear_history():116    global conversation_history117    conversation_history = []118    return jsonify({'success': True})119 120# Mapping Route121@app.route('/handle_mapping', methods=['POST'])122def handle_mapping():123    # Retrieve data from front end124    data = request.json125    start_location = data.get("start_location")126    end_location = data.get("end_location")127 128    # Geocode start and end locations129    start_coordinates = geocode_location(GRAPHHOPPER_API_KEY, start_location)130    end_coordinates = geocode_location(GRAPHHOPPER_API_KEY, end_location)131 132    if start_coordinates and end_coordinates:133        routing_url = f'{GRAPHHOPPER_URL}route?point={start_coordinates[0]},{start_coordinates[1]}&point={end_coordinates[0]},{end_coordinates[1]}&vehicle=foot&key={GRAPHHOPPER_API_KEY}'134 135        response = requests.get(routing_url)136 137        if response.status_code == 200:138            data = response.json()139 140            # Extract relevant information from the response141            distance_meters = data['paths'][0]['distance']142            time_milliseconds = data['paths'][0]['time']143 144            # Convert distance to miles (1 meter = 0.000621371 miles)145            distance_miles = distance_meters * 0.000621371146 147            # Convert time to hours and minutes148            total_time_seconds = time_milliseconds / 1000149            total_time_hours = int(total_time_seconds // 3600)150            total_time_minutes = int((total_time_seconds % 3600) // 60)151 152            # Check if the total distance is under 0.2 miles and display in feet153            if distance_miles < 0.2:154                distance = f'{distance_miles * 5280:.2f} feet'155            else:156                distance = f'{distance_miles:.2f} miles'157 158            # Print total time with hours and minutes only if not 0159            if total_time_hours > 0:160                total_time = f'{total_time_hours} hours and {total_time_minutes} minutes'161            else:162                total_time = f'{total_time_minutes} minutes'163 164            # Extract polyline data165            polyline_data = data['paths'][0]['points']166 167            # Decode polyline into list of coordinates168            decoded_polyline = polyline.decode(polyline_data)169 170            # Create a folium map171            map_obj = folium.Map(location=[start_coordinates[0], start_coordinates[1]], zoom_start=14)172 173            # Add markers for start and end locations with different colors174            folium.Marker(location=[start_coordinates[0], start_coordinates[1]], popup='Start', icon=folium.Icon(color='green')).add_to(map_obj)175            folium.Marker(location=[end_coordinates[0], end_coordinates[1]], popup='End', icon=folium.Icon(color='red')).add_to(map_obj)176 177            # Add a PolyLine to trace the route178            folium.PolyLine(decoded_polyline, color='blue', weight=5, opacity=0.7).add_to(map_obj)179 180            # Save the map to a temporary HTML file181            map_html = map_obj.get_root().render()182 183            # Initialize the message variable184            routeMessage = ''185 186            # Add total distance and total time to the message187            routeMessage += f'Starting Location: {start_location}\n'188            routeMessage += f'Ending Location: {end_location}\n\n'189            routeMessage += f'Total Distance: {distance}\n'190            routeMessage += f'Total Time: {total_time}\n\n'191 192            # Add directions to the message193            routeMessage += 'Directions:\n'194            for i, step in enumerate(data['paths'][0]['instructions'], start=1):195                distance_step_meters = step["distance"]196                distance_step_miles = distance_step_meters * 0.000621371197 198                # Check if the distance for the step is under 0.2 miles and display in feet199                if distance_step_miles < 0.2:200                    distance_step = f'{distance_step_miles * 5280:.2f} feet'201                else:202                    distance_step = f'{distance_step_miles:.2f} miles'203                # Append the step to the message204                routeMessage += f'{i}. {step["text"]} ({distance_step})\n'205 206            return jsonify({'message': routeMessage, 'map_html': map_html})207        else:208            return jsonify({'error': f'Routing Error: {response.status_code}, {response.text}'}), 500209    else:210        return jsonify({'error': 'Geocoding failed. Check your input locations.'}), 400211 212 213# Spotify Route214@app.route('/handle_spotify', methods=['POST'])215def handle_spotify():216    # Get access token217    spotify_access_token = get_mapping_access_token()218 219    # Extract data from front ent220    data = request.get_json()221    musicRequest = data.get('song')222 223    if spotify_access_token:224        headers = {225            'Authorization': 'Bearer {}'.format(spotify_access_token)226        }227        params = {228            'q': musicRequest,229            'type': 'track',230            'limit': 5231        }232        response = requests.get(SPOTIFY_API_URL + 'search', params=params, headers=headers)233        if response.status_code == 200:234            data = response.json()235            tracks = data['tracks']['items']  # Accessing the 'items' key of the 'tracks' dictionary236            formatted_tracks = []237            for track in tracks:238                formatted_track = {239                    'name': track['name'],240                    'album': track['album']['name'],241                    'artist': track['artists'][0]['name'],  # Assuming there's only one artist for simplicity242                    'image': track['album']['images'][2]['url'],  # Using the third image243                    'preview_url': track['id']244                }245                formatted_tracks.append(formatted_track)246 247            return jsonify(formatted_tracks)248        else:249            return jsonify({'status': 'Error', 'message': 'Unable to fetch serach results from spotify'})250    else:251            return jsonify({'status': 'Error', 'message': 'Unable to retrieve access token'})252 253# Play Music Route254@app.route('/play', methods=['POST'])255def play():256    track_id = request.form['track_id']257    access_token = get_mapping_access_token()258 259    if access_token:260        headers = {261            'Authorization': 'Bearer {}'.format(access_token)262        }263        response = requests.get(SPOTIFY_API_URL + 'tracks/{}'.format(track_id), headers=headers)264        if response.status_code == 200:265            data = response.json()266            preview_url = data.get('preview_url', "")267            return jsonify({"preview_url": preview_url})268        else:269            return "Error: Unable to fetch track preview from Spotify API"270    else:271        return "Error: Unable to retrieve access token"272 273if __name__ == '__main__':274    app.run(debug=True)275