tlavandier/OpenData-Bordeaux-RSE
1
1import streamlit as st2from folium import Map, Marker, Icon, Popup3from streamlit_folium import folium_static4from data_manager import get_data5from data_manager_bziiit import *6 7import os8from dotenv import load_dotenv9import openai10 11###############################################################################################12# PARTIE 0 : Récupération des données API bziiit et Bordeaux Métropole13###############################################################################################14 15def fetch_data():16 data, _ = get_data() # Récupération des données de Bordeaux Métropole17 bziiit_data = get_bziiit_data() # Récupération des données de Bziiit18 19 return data, bziiit_data20 21###############################################################################################22# PARTIE 1 : Le sélecteur d'entreprise23###############################################################################################24def display_company_selection_for_materiality(data):25 # Get a list of all company names26 companies = sorted(list(set(record['nom_courant_denomination'] for record in data)), key=str.lower)27 28 # Add default selection prompt to the beginning of the list29 companies.insert(0, "Sélectionner l'entreprise engagée à découvrir")30 31 selected_company = st.selectbox('Sélectionnez une entreprise', companies, index=0)32 33 # If the default selection is still selected, return None34 if selected_company == "Sélectionner l'entreprise engagée à découvrir":35 return None36 37 return selected_company # Return the selected company name38 39# Uniformiser les noms de champs40def normalize_company_name(record):41 # Gère les différences de noms de champs entre les APIs42 if 'nom_courant_denomination' in record:43 return record['nom_courant_denomination'].strip().lower()44 elif 'name' in record:45 return record['name'].strip().lower()46 return 'Unknown'47 48###############################################################################################49# PARTIE 3 : CONNEXION API MISTRAL 8x7b + AFFICHAGE DE LA CONVERSATION50###############################################################################################51 52# chargement du fichier .env53load_dotenv(".streamlit/.env")54 55def perform_chat(messages):56 YOUR_API_KEY = os.getenv("API_TOKEN_PERPLEXITYAI")57 if YOUR_API_KEY is None:58 raise Exception("API key not found. Please check your .env configuration.")59 client = openai.OpenAI(api_key=YOUR_API_KEY, base_url="https://api.perplexity.ai")60 61 response_stream = client.chat.completions.create(62 model="sonar-medium-online",63 messages=messages,64 stream=True65 )66 67 assistant_response = ""68 for chunk in response_stream:69 assistant_response += chunk.choices[0].delta.content70 71 st.write(assistant_response)72 73###############################################################################################74# PARTIE 4 : MATRICE DE MATERIALITE75###############################################################################################76def display_materiality_matrix(selected_company, data, bziiit_data):77 st.markdown("### La matrice de matérialité vue par l'IA bziiit / Mistral AI (8x7b)")78 option = st.radio(79 "Choisissez une option",80 ('Définition', 'Matrice simplifiée', 'Matrice détaillée'),81 index=082 )83 84 if option == 'Définition':85 st.write("""86 **La matrice de matérialité est un outil stratégique qui permet aux entreprises de classer et de prioriser les enjeux liés à la responsabilité sociale des entreprises (RSE) selon leur importance pour les parties prenantes et leur impact sur la performance de l'entreprise. Les trois points clés de la matrice de matérialité sont :**87 88 1. **Évaluation et priorisation des enjeux** : La matrice de matérialité aide à identifier et à classer les enjeux RSE en fonction de leur importance pour les parties prenantes et de leur impact sur la performance de l'entreprise. Cela permet aux entreprises de se concentrer sur les enjeux qui sont les plus importants pour leurs parties prenantes et pour leur propre succès.89 90 2. **Transparence et communication** : La matrice de matérialité encourage la transparence en matière de RSE en offrant un cadre pour la communication des résultats aux parties prenantes. Cela permet aux entreprises de renforcer leur image de marque et de répondre aux attentes croissantes en matière de durabilité.91 92 3. **Flexibilité et adaptabilité** : La matrice de matérialité est adaptable à différents contextes et tailles d'entreprises, offrant une flexibilité essentielle pour répondre aux besoins variés. Elle est un élément intégral de la planification stratégique d'une entreprise et facilite un reporting ESG transparent et informatif.93 """)94 95 96 elif option == 'Matrice simplifiée':97 company_data = next((item for item in data if item['nom_courant_denomination'].strip().lower() == selected_company.strip().lower()), None)98 bziiit_brand_data = next((brand for brand in bziiit_data if brand['type'] == 'brand' and brand['name'].strip().lower() == selected_company.strip().lower()), None)99 if company_data and bziiit_brand_data:100 run_perplexity_chat_simplified(company_data['nom_courant_denomination'], bziiit_brand_data['description'], company_data['action_rse'])101 102 103 elif option == 'Matrice détaillée':104 company_data = next((item for item in data if item['nom_courant_denomination'].strip().lower() == selected_company.strip().lower()), None)105 bziiit_brand_data = next((brand for brand in bziiit_data if brand['type'] == 'brand' and brand['name'].strip().lower() == selected_company.strip().lower()), None)106 if company_data and bziiit_brand_data:107 run_perplexity_chat_detailed(company_data['nom_courant_denomination'], bziiit_brand_data['description'], company_data['action_rse'])108 109###############################################################################################110# PARTIE 5 : FONCTIONS MATRICE DE MATERIALITE111###############################################################################################112 113def run_perplexity_chat_simplified(company_name, company_description, company_rse_action):114 question = f"L'entreprise {company_name}, dont l'activité est {company_description}, a pour action RSE principale {company_rse_action}. Quels peuvent être les principaux éléments de sa matrice de matérialité ? REPONDS TOUJOURS EN FRANCAIS"115 messages = [116 {"role": "system", "content": "You are an artificial intelligence assistant and you need to engage in a helpful, detailed, polite conversation with a user."},117 {"role": "user", "content": question}118 ]119 st.markdown("**Question posée :**")120 st.write(question)121 st.markdown("**Réponse IA :**")122 perform_chat(messages)123 124def run_perplexity_chat_detailed(company_name, company_description, company_rse_action):125 question = f"L'entreprise {company_name}, dont l'activité est {company_description}, a pour action RSE principale {company_rse_action}. Fais moi une présentation détaillée TOUJOURS EN FRANCAISE de ce que pourraient être sa matrice de matérialité ?"126 messages = [127 {"role": "system", "content": "You are an artificial intelligence assistant and you need to engage in a helpful, detailed, polite conversation with a user."},128 {"role": "user", "content": question}129 ]130 st.markdown("**Question posée :**")131 st.write(question)132 st.markdown("**Réponse IA :**")133 perform_chat(messages)134 135 