Commit ·
fab5009
1
Parent(s): 98691d1
IA avec API Perplexity
Browse filesFiles changed (14)
- .gitignore+1
- DATA IA RSE Bordeaux Metropole.pngAdded
- RECO IA RSE Bordeaux Metropole.pngAdded
- app.py+37-5
- collaborons.pyAdded+128
- data_manager.py+39-1
- data_manager_bziiit.py+49-7
- documentations.pyAdded+28
- entreprises_labellisees.pyAdded+45
- inspirezvous.pyAdded+256
- labelRSE.py+3-1
- localisation.py+1-2
- partiesprenantes.pyAdded+156
- requirements.txt+1
1__pycache__/12__pycache__/.streamlit/secrets.toml
6 unmodified lines789101112131415161718192021222312 unmodified lines3637383940414243444546474849506 unmodified linesfrom statistiques import main as display_statisticsfrom ActionsRSE import display_actions_rsefrom AnalyseActionsRSE import display_analyse_actions_rse# Import modifiédes fonctions liées aux scriptsfrom projetRSE import display_rse_projectsfrom labelRSE import display_rse_labelsfrom marquesengagees import display_engaged_brandsdef main():st.sidebar.title("OPEN DATA & IA au service de la RSE")section_principale = st.sidebar.radio("Choisissez votre section",["Data Bordeaux métropole", "Data bziiit"])if section_principale == "Data Bordeaux métropole":12 unmodified lineselif app_mode == "Analyse actions RSE":display_analyse_actions_rse()elif section_principale == "Data bziiit":ia_mode = st.sidebar.radio("Choisissez votre sous-section",["Labels RSE", "Projets RSE"])if ia_mode == "Labels RSE":display_rse_labels()elif ia_mode == "Projets RSE":display_rse_projects()# Instructions communes à toutes les sectionsst.sidebar.markdown("---")6 unmodified lines789101112131415161718192021222324252627282912 unmodified lines42434445464748495051525354555657585960616263646566676869707172737475767778798081826 unmodified linesfrom statistiques import main as display_statisticsfrom ActionsRSE import display_actions_rsefrom AnalyseActionsRSE import display_analyse_actions_rsefrom partiesprenantes import display_materiality_partiesprenantes# Import modifiédes fonctions liées aux scriptsfrom projetRSE import display_rse_projectsfrom labelRSE import display_rse_labelsfrom entreprises_labellisees import display_labelled_companiesfrom inspirezvous import *from collaborons import display_company_selection_for_materiality,display_materiality_matrixfrom documentations import display_documentationdef main():st.markdown(":point_left: Cliquez pour vous inspirer", unsafe_allow_html=True)st.sidebar.title("OPEN DATA & IA au service de la RSE")section_principale = st.sidebar.radio("Choisissez votre section",["Data Bordeaux métropole", "Data bziiit","IA RSE","Documentation"])if section_principale == "Data Bordeaux métropole":12 unmodified lineselif app_mode == "Analyse actions RSE":display_analyse_actions_rse()elif section_principale == "Data bziiit":ia_mode = st.sidebar.radio("Choisissez votre sous-section",["Labels RSE", "Entreprises labellisées", "Fiches entreprises"])if ia_mode == "Labels RSE":display_rse_labels()elif ia_mode == "Entreprises labellisées":display_labelled_companies()elif ia_mode == "Fiches entreprises":data, bziiit_data = fetch_data()selected_company = display_company_selection(data)display_company_info(data, bziiit_data, selected_company)elif section_principale == "IA RSE":ia_mode = st.sidebar.radio("Choisissez votre sous-section",["Parties prenantes", "Matrice de matérialité"])if ia_mode == "Parties prenantes":data, bziiit_data = fetch_data()selected_company = display_company_selection_for_materiality(data)if selected_company:display_materiality_partiesprenantes(selected_company, data, bziiit_data)elif ia_mode == "Matrice de matérialité":data, bziiit_data = fetch_data()selected_company = display_company_selection_for_materiality(data)if selected_company:display_materiality_matrix(selected_company, data, bziiit_data)elif section_principale == "Documentation":display_documentation()# Instructions communes à toutes les sectionsst.sidebar.markdown("---")
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128import streamlit as stfrom openai import OpenAIfrom folium import Map, Marker, Icon, Popupfrom streamlit_folium import folium_staticfrom data_manager import get_datafrom data_manager_bziiit import *from ISO26000 import classify_actions_rse_ISO26000from urllib.parse import urlparse
################################################################################################ PARTIE 0 : Récupération des données API bziiit et Bordeaux Métropole###############################################################################################
def fetch_data(): data, _ = get_data() # Récupération des données de Bordeaux Métropole bziiit_data = get_bziiit_data() # Récupération des données de Bziiit
return data, bziiit_data
################################################################################################ PARTIE 1 : Le sélecteur d'entreprise###############################################################################################def display_company_selection_for_materiality(data): # Get a list of all company names companies = sorted(list(set(record['nom_courant_denomination'] for record in data)), key=str.lower)
# Add default selection prompt to the beginning of the list companies.insert(0, "Sélectionner l'entreprise engagée à découvrir")
selected_company = st.selectbox('Sélectionnez une entreprise', companies, index=0)
# If the default selection is still selected, return None if selected_company == "Sélectionner l'entreprise engagée à découvrir": return None
return selected_company # Return the selected company name
# Uniformiser les noms de champsdef normalize_company_name(record): # Gère les différences de noms de champs entre les APIs if 'nom_courant_denomination' in record: return record['nom_courant_denomination'].strip().lower() elif 'name' in record: return record['name'].strip().lower() return 'Unknown'
################################################################################################ PARTIE 3 : CONNEXION API MISTRAL 8x7b + AFFICHAGE DE LA CONVERSATION###############################################################################################
def perform_chat(messages): YOUR_API_KEY = st.secrets["API_TOKEN_PERPLEXITYAI"] client = OpenAI(api_key=YOUR_API_KEY, base_url="https://api.perplexity.ai")
response_stream = client.chat.completions.create( model="mixtral-8x7b-instruct", messages=messages, stream=True )
assistant_response = "" for chunk in response_stream: assistant_response += chunk.choices[0].delta.content
st.write(assistant_response)
################################################################################################ PARTIE 4 : MATRICE DE MATERIALITE###############################################################################################def display_materiality_matrix(selected_company, data, bziiit_data): st.markdown("### La matrice de matérialité vue par l'IA bziiit / Mistral AI (8x7b)") option = st.radio( "Choisissez une option", ('Définition', 'Matrice simplifiée', 'Matrice détaillée'), index=0 )
if option == 'Définition': st.write(""" **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 :**
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.
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é.
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. """) elif option == 'Matrice simplifiée': company_data = next((item for item in data if item['nom_courant_denomination'].strip().lower() == selected_company.strip().lower()), None) bziiit_brand_data = next((brand for brand in bziiit_data if brand['type'] == 'brand' and brand['name'].strip().lower() == selected_company.strip().lower()), None) if company_data and bziiit_brand_data: run_perplexity_chat_simplified(company_data['nom_courant_denomination'], bziiit_brand_data['description'], company_data['action_rse']) elif option == 'Matrice détaillée': company_data = next((item for item in data if item['nom_courant_denomination'].strip().lower() == selected_company.strip().lower()), None) bziiit_brand_data = next((brand for brand in bziiit_data if brand['type'] == 'brand' and brand['name'].strip().lower() == selected_company.strip().lower()), None) if company_data and bziiit_brand_data: run_perplexity_chat_detailed(company_data['nom_courant_denomination'], bziiit_brand_data['description'], company_data['action_rse'])
################################################################################################ PARTIE 5 : FONCTIONS MATRICE DE MATERIALITE###############################################################################################
def run_perplexity_chat_simplified(company_name, company_description, company_rse_action): 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" messages = [ {"role": "system", "content": "You are an artificial intelligence assistant and you need to engage in a helpful, detailed, polite conversation with a user."}, {"role": "user", "content": question} ] st.markdown("**Question posée :**") st.write(question) st.markdown("**Réponse IA :**") perform_chat(messages)
def run_perplexity_chat_detailed(company_name, company_description, company_rse_action): 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é ?" messages = [ {"role": "system", "content": "You are an artificial intelligence assistant and you need to engage in a helpful, detailed, polite conversation with a user."}, {"role": "user", "content": question} ] st.markdown("**Question posée :**") st.write(question) st.markdown("**Réponse IA :**") perform_chat(messages)
123456789101112import requestsdef get_data():url = "https://opendata.bordeaux-metropole.fr/api/records/1.0/search/?dataset=met_etablissement_rse&q=&rows=100"response = requests.get(url)if response.status_code == 200:data = response.json()records = data.get("records", [])return [record["fields"] for record in records], data.get("nhits", 0)else:return [], 01234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950import requests# URL de base de l'API bziiitdef get_data():url = "https://opendata.bordeaux-metropole.fr/api/records/1.0/search/?dataset=met_etablissement_rse&q=&rows=100"response = requests.get(url)if response.status_code == 200:data = response.json()records = data.get("records", [])if records:print(records[0]) # Print an example record# Ensure every record includes the 'nom_courant_denomination' keyfor record in records:if 'nom_courant_denomination' not in record["fields"]:record["fields"]['nom_courant_denomination'] = 'Unknown'return [record["fields"] for record in records], data.get("nhits", 0)else:return [], 0"""Exemple de données récupérées via l'API de Bordeaux Métropole:st.write("Normalized Company Data:", company_data)Normalized Company Data:{"point_geo":[0:44.881367292819351:-0.5145680443292318]"tranche_effectif_etab":"Non déclaré""siret":"8,1383E+13""naf_section":"J""code_naf":"6510Z""ban_x_lambert_93":422559.4"code_postal":"33310""naf_groupe":"620""libelle_section_naf":"Information et communication""libelle_groupe_naf":"Programmation, conseil et autres activités informatiques""nom_courant_denomination":"bziiit""tranche_effectif_entreprise":"6 à 9 Salariés""commune":"LORMONT""action_rse":"Face à l'urgence de réduire l'empreinte carbone du numérique, nous avons mis en place le tryptique MESURER - FORMER - REDUIRE sur l'ensemble de nos usages (cloud, intelligence artificielle)""hierarchie_naf":"Information et communication/Programmation, conseil et autres activités informatiques/libelle_naf""adresse_numero_et_voie":"6 Rue du Courant""ban_y_lambert_93":6426418.2}"""
1234567891011121314151617181920212223242526272829import requests# URL de base de l'API bziiitBASE_URL = "https://bziiitapi-api.azurewebsites.net"def get_labels():# Récupère les labels RSE depuis l'API bziiitresponse = requests.get(f"{BASE_URL}/opendata/labels")if response.status_code == 200:return response.json()["response"]else:return []def get_rse_projects():# Récupère les projets RSE depuis l'API bziiitresponse = requests.get(f"{BASE_URL}/opendata/bordeaux-rse/projects")if response.status_code == 200:return response.json()["response"]else:return []def get_engaged_brands():# Récupère les marques engagées depuis l'API bziiitresponse = requests.get(f"{BASE_URL}/opendata/bordeaux-rse/brands")if response.status_code == 200:return response.json()["response"]else:return []1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071import requestsimport streamlit as st# URL de base de l'API bziiitBASE_URL = "https://bziiitapi-api.azurewebsites.net"# Fonction de récupération des labelsdef get_labels():url = f"{BASE_URL}/opendata/labels"response = requests.get(url)if response.status_code == 200:return response.json()["response"]else:st.error(f"Échec de récupération des labels: {response.text}")return []# Fonction de récupération des projets RSEdef get_rse_projects():url = f"{BASE_URL}/opendata/bordeaux-rse/projects"response = requests.get(url)if response.status_code == 200:return response.json()["response"]else:st.error(f"Échec de récupération des projets RSE: {response.text}")return []# Fonction de récupération des entreprisesdef get_engaged_brands():url = f"{BASE_URL}/opendata/bordeaux-rse/brands"response = requests.get(url)if response.status_code == 200:return response.json()["response"]else:st.error(f"Échec de récupération des marques engagées: {response.text}")return []# Fonction consolidant les données labels + projets RSE + marquesdef get_bziiit_data():labels = get_labels()rse_projects = get_rse_projects()engaged_brands = get_engaged_brands()bziiit_data = []# Assurez-vous d'utiliser 'name' pour bziiit data et ajoutez une distinction de typefor label in labels:bziiit_data.append({'type': 'label', # Ajout du type'name': label.get('name', 'Unknown'),'description': label.get('description', 'Unknown'),'logo_url': label.get('logo_url', 'Unknown'),'labels': [label] # Stocke l'objet label entier si nécessaire})for project in rse_projects:bziiit_data.append({'type': 'project', # Ajout du type'name': project.get('name', 'Unknown'),'labels': project.get('labels', []) # Assurez-vous que 'labels' est une liste dans le JSON de réponse})for brand in engaged_brands:bziiit_data.append({'type': 'brand', # Ajout du type'name': brand.get('name', 'Unknown'),'logo_url': brand.get('logo_url', 'Unknown'), # Assurez-vous que 'logo_url' est une URL valide'description': brand.get('description', 'Unknown'),'labels': brand.get('labels', [])})return bziiit_data
12345678910111213141516171819202122232425262728import streamlit as st
def display_documentation():
st.markdown("<hr style='border-color: darkgrey;'>", unsafe_allow_html=True) # Add this line
st.title("OPEN DATA IA RSE Bordeaux Métropole") st.markdown("## La Data et l'IA au service des démarches RSE (Economie, Social, Environnemental)")
st.image("DATA IA RSE Bordeaux Metropole.png", caption="Data IA RSE Bordeaux Metropole") st.image("RECO IA RSE Bordeaux Metropole.png", caption="RECO IA RSE Bordeaux Metropole")
# Credits
st.markdown("""<hr style='border-color: darkgrey;'>""", unsafe_allow_html=True)
st.markdown(""" <div class="credits"> <p>Data Bordeaux Métropole : Licence MIT 2024 </p> <p>Data bziiit : Licence MIT 2024</p> <p>API IA : Perplexity</p> <p>Avril 2004</p> </div> """, unsafe_allow_html=True)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445import streamlit as stfrom data_manager_bziiit import get_bziiit_data
def display_labelled_companies(): st.markdown("## Entreprises Labellisées (source OPEN DATA bziiit)") st.markdown("### Découvrez les entreprises engagées avec au moins un label RSE")
# Récupération des données bziiit bziiit_data = get_bziiit_data()
# Filtrage des entreprises ayant au moins un label labelled_companies = [brand for brand in bziiit_data if brand['type'] == 'brand' and len(brand.get('labels', [])) > 0]
# Calcul du nombre de labels par entreprise for brand in labelled_companies: brand['label_count'] = len(brand['labels'])
# Calcul et affichage du nombre et du pourcentage d'entreprises labellisées total_companies = len([brand for brand in bziiit_data if brand['type'] == 'brand']) labelled_companies_count = len(labelled_companies) percentage_labelled = round((labelled_companies_count / total_companies) * 100) st.markdown(f"**Nb entreprises labellisées :** {labelled_companies_count} ({percentage_labelled}%)")
# Tri des entreprises par le nombre de labels, ordre décroissant labelled_companies.sort(key=lambda x: x['label_count'], reverse=True)
# Affichage des entreprises for i in range(0, len(labelled_companies), 5): cols = st.columns(5) image_placeholders = [col.empty() for col in cols] padding_placeholders = [col.empty() for col in cols] text_placeholders = [col.empty() for col in cols] for j in range(5): if i + j < len(labelled_companies): company = labelled_companies[i + j] with cols[j]: if company['logo_url'] != 'Unknown': image_placeholders[j].image(company['logo_url'], width=100) padding_placeholders[j].write("") # This will act as padding text_placeholders[j].write(company['name']) text_placeholders[j].write(f"Nb labels : {company['label_count']}")
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256import streamlit as stimport refrom folium import Map, Marker, Icon, Popupfrom streamlit_folium import folium_staticfrom data_manager import get_datafrom data_manager_bziiit import *from ISO26000 import classify_actions_rse_ISO26000from bs4 import BeautifulSoupfrom urllib.parse import urlparse
################################################################################################ PARTIE 0 : Récupération des données API bziiit et Bordeaux Métropole###############################################################################################
def fetch_data(): data, _ = get_data() # Récupération des données de Bordeaux Métropole bziiit_data = get_bziiit_data() # Récupération des données de Bziiit
return data, bziiit_data
################################################################################################ PARTIE 1 : Le sélecteur d'entreprise###############################################################################################
def display_company_selection(data): # Get a list of all company names companies = sorted(list(set(record['nom_courant_denomination'] for record in data)), key=str.lower)
selected_company = st.selectbox('Sélectionnez une entreprise', companies) return selected_company # Return the selected company name
# Uniformiser les noms de champsdef normalize_company_name(record): # Gère les différences de noms de champs entre les APIs if 'nom_courant_denomination' in record: return record['nom_courant_denomination'].strip().lower() elif 'name' in record: return record['name'].strip().lower() return 'Unknown'
################################################################################################ PARTIE 2 : AFFICHAGE OPEN DATA BORDEAUX METROPOLE###############################################################################################
def display_company_info(data, bziiit_data, selected_company): normalized_selected = normalize_company_name({'name': selected_company}) # Assurez-vous que cette fonction normalise correctement comme expliqué dans l'étape 1. company_data = next((record for record in data if normalize_company_name(record) == normalized_selected), None) bziiit_company_data = next((record for record in bziiit_data if normalize_company_name(record) == normalized_selected), None)
classified_data = classify_actions_rse_ISO26000(data) # Normalize the company name for comparison normalized_selected = normalize_company_name({'name': selected_company})
# Find the company in the classified data company_category = None for category, companies in classified_data.items(): if any(normalize_company_name(company) == normalized_selected for company in companies): company_category = category break
if bziiit_company_data is None: bziiit_company_data = {}
st.markdown("""<hr style='border-color: darkgrey;'>""", unsafe_allow_html=True) if company_data: st.markdown("### Source OPEN DATA Bordeaux Métropole") st.write(f"**Nom de l'entreprise:** {company_data.get('nom_courant_denomination', 'Non disponible')}") col10, col20 = st.columns(2)
with col10: if 'point_geo' in company_data and len(company_data['point_geo']) == 2: lat, lon = company_data['point_geo'] m = Map(location=[lat, lon], zoom_start=10) popup_html = f""" <div style="width:300px;"> <b>{company_data.get('nom_courant_denomination', 'Sans nom')}</b><br><br> <b>Action RSE:</b><br> {company_data.get('action_rse', 'Non spécifiée')}<br><br> <hr style="margin: 1px 0; border: none; border-top: 1px solid #ccc;"> <b>Secteur d'activité:</b> {company_data.get('libelle_section_naf', 'Non spécifié')} </div> """ icon = Icon(icon="leaf", prefix='fa', color='green') Marker([lat, lon], icon=icon, popup=Popup(popup_html, max_width=500)).add_to(m) folium_static(m, width=330, height=500) else: st.write("**Position GPS non disponible pour cette entreprise.**")
with col20: st.write(f"**Nom de l'entreprise :** {company_data.get('nom_courant_denomination', 'Non disponible')}") st.write(f"**Commune :** {company_data.get('commune', 'Non disponible')}") st.write(f"**Section NAF :** {company_data.get('libelle_section_naf', 'Non disponible')}") st.write(f"**Effectif :** {company_data.get('tranche_effectif_entreprise', 'Non spécifié')}") action_rse = company_data.get('action_rse', 'Non spécifié') st.write(f"**Action RSE :** {action_rse}") if action_rse != 'Non spécifié': if company_category: st.write(f"**Classification ISO 26000 (via IA) :** {company_category}") else: st.write("**Classification ISO 26000:** Catégorie non déterminée")
else: st.error("Aucune donnée disponible pour cette entreprise depuis l'API Bordeaux Métropole.") ############################################################################################### # PARTIE 3 : AFFICHAGE OPEN DATA bziiit###############################################################################################
def get_labels(): url = f"{BASE_URL}/opendata/labels" response = requests.get(url) if response.status_code == 200: return response.json()["response"] else: st.error(f"Échec de récupération des labels: {response.text}") return [] st.markdown("""<hr style='border-color: darkgrey;'>""", unsafe_allow_html=True)
if bziiit_company_data: st.markdown("### Source OPEN DATA bziiit")
# Assurez-vous d'avoir les informations nécessaires logo_url = bziiit_company_data.get('logo_url', '') website_url = bziiit_company_data.get('website_url', '')
# Affichez le logo if logo_url: st.markdown(f'<div style="text-align: center;"><img src="{logo_url}" style="width:120px;" /></div>', unsafe_allow_html=True) else: st.markdown('<div style="text-align: center;"><em style="font-size: small;">Logo non disponible</em></div>', unsafe_allow_html=True)
# Récupérez la description description = bziiit_company_data.get('description', '') # Utilisez une regex pour trouver les URL dans la description website_url = re.findall(r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', description) # Vérifiez si une URL a été trouvée if website_url: # Prenez la première URL trouvée website_url = website_url[0] st.markdown(f'<div style="text-align: center;">[Site web de l\'entreprise]({website_url})</div>', unsafe_allow_html=True) else: st.markdown('<div style="text-align: center;"><em style="font-size: small;">URL du site web non disponible</em></div>', unsafe_allow_html=True)
description_html = bziiit_company_data.get('description', 'Description non disponible') description_text = BeautifulSoup(description_html, "html.parser").get_text() st.write("📝 **Description de l'entreprise:**") st.write(description_text)
st.markdown("🏷️ **Labels / Certifications RSE - Qualité :**") labels = get_labels() # Get the labels using the get_labels function label_data = bziiit_company_data.get('labels', []) if not label_data: st.write("Pas de Labels / Certifications RSE - Qualité actuellement.") else: # ... for i in range(0, len(label_data), 2): # Loop through labels two at a time cols = st.columns(2) # Create two columns for j in range(2): # Loop through the two labels if i + j < len(label_data): # Check if there is a label to process label = label_data[i + j] label_name = label.get("name", "Label non spécifié") # Find the corresponding label in the labels data label_info = next((l for l in labels if l.get("name") == label_name), None) if label_info: # Only process labels with info label_description = label_info.get("description", "Description non disponible") # Get the label description from the label info logo_url = label_info.get("logo_url") # Get the logo URL from the label info try: # Display the image in the corresponding column with a tooltip cols[j].markdown(f'<div style="text-align: center;"><a href="#" title="{label_description}"><img src="{logo_url}" alt="{label_name}" style="width:120px;"></a><p>{label_name}</p></div>', unsafe_allow_html=True) except Exception as e: st.error(f"Erreur lors de l'affichage de l'image : {e}") # ... if st.button('Ici pour visualiser le mail à envoyer pour référencer un nouveau label / certification RSE - Qualité'): st.markdown(""" **Objet email :** Demande de référencement Certification / Label RSE - Qualité
**Corps email :** Bonjour,
Ci-dessous le lien publique vers la certification / label RSE - Qualité de notre entreprise pour référencement dans votre plateforme OPEN DATA IA RSE Bordeaux Métropole
URL à renseigner - 01 : URL à renseigner - 02 : URL à renseigner - 03 : ...
Nom du demandeur : Qualité ou statut :
Destinataire : info@bziiit.com
Merci par avance de votre aide pour développer la visibilité de vos Labels / Certifications L'équipe OPEN DATA IA RSE Bordeaux Métropole """, unsafe_allow_html=True)
else: st.write("**Aucune donnée bziiit disponible pour cette entreprise.**")
def is_valid_url(url): try: response = requests.head(url) return response.status_code == 200 except requests.RequestException: return False
"""################################################################################################ PARTIE 5 : AFFICHAGE INSPIREZ VOUS###############################################################################################def display_similar_companies(data, selected_company): classified_data = classify_actions_rse_ISO26000(data) company_data = next((record for record in data if record['nom_courant_denomination'] == selected_company), None) if company_data: action_rse = company_data.get('action_rse', 'Unknown').lower() for category, companies in classified_data.items(): if any(company.get('action_rse', 'Unknown').lower() == action_rse for company in companies):""" # st.markdown("""<hr style='border-color: darkgrey;'>""", unsafe_allow_html=True)""" st.write("Ces organisations pourraient également vous inspirer") max_pages = (len(companies) - 1) // 5 + 1 cols = st.columns([1,1,1,1,1]) if cols[1].button('Précédent'): page = max(page - 1, 1) page = cols[2].number_input('Page', min_value=1, max_value=max_pages, value=1, step=1) if cols[3].button('Suivant'): page = min(page + 1, max_pages) companies_to_display = companies[(page - 1) * 5:page * 5] st.write(f"Page: {page}") # Debugging line st.write(f"Companies to display: {companies_to_display}") # Debugging line for i, company in enumerate(companies_to_display): st.write(f"Company: {company}") # Debugging line logo_url = company.get('logo', 'https://opendata.bordeaux-metropole.fr/assets/theme_image/Open%20data%20-%20Pictos%2050px%20x%2050px-03.jpg') if is_valid_url(logo_url): cols[i].image(logo_url, width=50) else: cols[i].image('https://opendata.bordeaux-metropole.fr/assets/theme_image/Open%20data%20-%20Pictos%2050px%20x%2050px-03.jpg', width=50) cols[i].write(f"**{company.get('name', 'Unknown')}**") cols[i].write(f"{company.get('action_rse', 'Unknown')[:30]}")"""9 unmodified lines1011121314151617181920219 unmodified lineslabels_option = st.radio("Choisissez les labels à afficher :",("Tous les labels / Certifications DATA bziiit", "Labels / Certifications des organisations engagées Bdx Métropole"))st.markdown("""<hr style='border-color: darkgrey;'>""", unsafe_allow_html=True)labels = get_labels()if labels_option == "Tous les labels / Certifications DATA bziiit":labels.sort(key=lambda x: x['name'])else:9 unmodified lines10111213141516171819202122239 unmodified lineslabels_option = st.radio("Choisissez les labels à afficher :",("Labels / Certifications des organisations engagées Bdx Métropole", "Tous les labels / Certifications DATA bziiit"))st.markdown("""<hr style='border-color: darkgrey;'>""", unsafe_allow_html=True)labels = get_labels()if labels_option == "Tous les labels / Certifications DATA bziiit":labels.sort(key=lambda x: x['name'])else:
123438 unmodified lines43444546from folium import Map, Marker, Icon, Popupfrom streamlit_folium import folium_staticimport streamlit as st38 unmodified linesfolium_static(m)if __name__ == "__main__":display_map()12338 unmodified lines42434445from folium import Map, Marker, Icon, Popupfrom streamlit_folium import folium_staticimport streamlit as st38 unmodified linesfolium_static(m)if __name__ == "__main__":display_map()
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156import streamlit as stfrom openai import OpenAIfrom folium import Map, Marker, Icon, Popupfrom streamlit_folium import folium_staticfrom data_manager import get_datafrom data_manager_bziiit import *
################################################################################################ PARTIE 0 : Récupération des données API bziiit et Bordeaux Métropole###############################################################################################
def fetch_data(): data, _ = get_data() # Récupération des données de Bordeaux Métropole bziiit_data = get_bziiit_data() # Récupération des données de Bziiit
return data, bziiit_data
################################################################################################ PARTIE 1 : Le sélecteur d'entreprise###############################################################################################def display_company_selection_for_materiality(data): # Get a list of all company names companies = sorted(list(set(record['nom_courant_denomination'] for record in data)), key=str.lower)
# Add default selection prompt to the beginning of the list companies.insert(0, "Sélectionner l'entreprise engagée à découvrir")
selected_company = st.selectbox('Sélectionnez une entreprise', companies, index=0)
# If the default selection is still selected, return None if selected_company == "Sélectionner l'entreprise engagée à découvrir": return None
return selected_company # Return the selected company name
# Uniformiser les noms de champsdef normalize_company_name(record): # Gère les différences de noms de champs entre les APIs if 'nom_courant_denomination' in record: return record['nom_courant_denomination'].strip().lower() elif 'name' in record: return record['name'].strip().lower() return 'Unknown'
################################################################################################ PARTIE 3 : CONNEXION API sonar-medium-online + AFFICHAGE DE LA CONVERSATION###############################################################################################
def perform_chat(messages): YOUR_API_KEY = st.secrets["API_TOKEN_PERPLEXITYAI"] client = OpenAI(api_key=YOUR_API_KEY, base_url="https://api.perplexity.ai")
response_stream = client.chat.completions.create( model="sonar-medium-online", messages=messages, stream=True )
assistant_response = "" for chunk in response_stream: assistant_response += chunk.choices[0].delta.content
st.write(assistant_response)
################################################################################################ PARTIE 4 : PARTIES PRENANTES###############################################################################################def display_materiality_partiesprenantes(selected_company, data, bziiit_data): st.markdown("### Les parties prenantes identifiées par l'IA bziiit / Perplexity - sonar-medium-online") option = st.radio( "Choisissez une option", ('Définition', 'Parties prenantes prioritaires', 'Parties prenantes détaillées'), index=0 )
if option == 'Définition': st.write(""" **L'identification et l'implication des parties prenantes dans une démarche de Responsabilité Sociale des Entreprises (RSE) sont cruciales pour le succès et la légitimité des actions entreprises. Voici une synthèse en trois points clés de leur importance :
1. **Identification des parties prenantes pour une stratégie RSE inclusive**: - L'identification des parties prenantes est la première étape essentielle pour comprendre qui sont les acteurs impactés par les activités de l'entreprise et qui peuvent influencer ses décisions[4]. - Cela inclut un large éventail d'acteurs tels que les employés, clients, fournisseurs, actionnaires, communautés locales, ONG et l'État[4][5]. - La norme ISO 26000 recommande d'intégrer les parties prenantes à tous les niveaux de la démarche RSE, ce qui permet de reconnaître et de répondre à leurs intérêts et attentes[3][5].
2. **Hiérarchisation et cartographie pour prioriser les actions**: - Après l'identification, il est important de qualifier et de hiérarchiser les parties prenantes pour déterminer leur influence et leurs attentes, ainsi que les impacts de l'entreprise sur eux[4]. - La cartographie des parties prenantes permet de visualiser et de prioriser les relations en fonction de leur importance stratégique pour l'entreprise[2]. - Cette étape aide à concentrer les ressources et les efforts sur les parties prenantes clés et à élaborer des stratégies d'engagement adaptées[2][4].
3. **Engagement des parties prenantes pour une RSE efficace et crédible**: - L'engagement des parties prenantes est fondamental pour construire une démarche RSE crédible et pour obtenir leur soutien[4][5]. - Il s'agit d'établir un dialogue constructif, de définir des objectifs SMART et de mettre en place des actions concrètes pour répondre aux attentes des parties prenantes[4]. - L'implication active des parties prenantes internes et externes favorise la transparence, renforce la confiance et améliore l'acceptabilité sociale des activités de l'entreprise[6].
En somme, l'identification et l'implication des parties prenantes sont des processus interdépendants qui permettent aux entreprises de développer une stratégie RSE cohérente, de gérer les risques et d'optimiser leur impact social et environnemental.
Citations: [1] https://www.greenflex.com/actualites/articles/rse-parties-prenantes/ [2] https://datavalue-consulting.com/cartographie-partie-prenante-rse/ [3] https://www.novethic.fr/entreprises-responsables/qui-sont-les-parties-prenantes-de-lentreprise.html [4] https://www.cabinetdesaintfront.fr/publications/comment-engager-ses-parties-prenantes/ [5] https://www.labellucie.com/parties-prenantes-rse [6] https://blog.hubspot.fr/marketing/parties-prenantes-rse [7] https://www.erudit.org/fr/revues/mi/2013-v17-n2-mi0560/1015400ar/ [8] https://www.civitime.com/rse/parties-prenantes [9] https://speaknact.fr/fr/blog/article/561--impliquer-ses-parties-prenantes-pour-une-rse-efficace [10] https://www.abeautifulgreen.com/le-role-des-parties-prenantes-et-la-rse/ [11] https://www.cairn.info/revue-management-et-avenir-2014-2-page-73.htm [12] https://www.squadeasy.com/blog/qui-sont-les-parties-prenantes-dune-entreprise [13] https://www.associatheque.fr/fr/fichiers/bao/fiche-memo-RSE-DD-les-etapes-de-la-demarche.pdf [14] https://greenly.earth/fr-fr/blog/guide-entreprise/rse-partie-prenantes [15] https://www.veolia.com/fr/veolia-group/engagement-rse/engagement-parties-prenantes
""") elif option == 'Parties prenantes prioritaires': company_data = next((item for item in data if item['nom_courant_denomination'].strip().lower() == selected_company.strip().lower()), None) bziiit_brand_data = next((brand for brand in bziiit_data if brand['type'] == 'brand' and brand['name'].strip().lower() == selected_company.strip().lower()), None) if company_data and bziiit_brand_data: run_perplexity_chat_parties_prenantes_prioritaires(company_data['nom_courant_denomination'], bziiit_brand_data['description'], company_data['action_rse']) elif option == 'Parties prenantes détaillées': company_data = next((item for item in data if item['nom_courant_denomination'].strip().lower() == selected_company.strip().lower()), None) bziiit_brand_data = next((brand for brand in bziiit_data if brand['type'] == 'brand' and brand['name'].strip().lower() == selected_company.strip().lower()), None) if company_data and bziiit_brand_data: run_perplexity_chat_parties_prenantes_detailed(company_data['nom_courant_denomination'], bziiit_brand_data['description'], company_data['action_rse'])
################################################################################################ PARTIE 5 : FONCTIONS PARTIES PRENANTES###############################################################################################
def run_perplexity_chat_parties_prenantes_prioritaires(company_name, company_description, company_rse_action): question = f"En tant que spécialiste RSE et notamment de l'identification des parties prenantes d'une entreprise, tu es chargé d'identifier les parties prenantes prioritaires de l'entreprise dont : le nom est {company_name}, l'activité est {company_description}, ses principales actions RSE sont {company_rse_action}. Affiche les résultats TOUJOURS EN FRANCAIS classés par catégories de parties prenantes et cite les sources en bas de ta réponse." messages = [ {"role": "system", "content": "You are an artificial intelligence assistant and you need to engage in a helpful, detailed, polite conversation with a user."}, {"role": "user", "content": question} ] st.markdown("**Question posée :**") st.write(question) st.markdown("**Réponse IA :**") perform_chat(messages)
def run_perplexity_chat_parties_prenantes_detailed(company_name, company_description, company_rse_action): question = f"En tant que spécialiste RSE et notamment de l'identification des parties prenantes d'une entreprise, tu es chargé d'identifier l'ensemble des parties prenantes de l'entreprise dont : le nom est {company_name}, l'activité est {company_description}, ses principales actions RSE sont {company_rse_action},. Affiche les résultats détaillés TOUJOURS EN FRANCAIS classés par catégories de parties prenantes et cite les sources en bas de ta réponse." messages = [ {"role": "system", "content": "You are an artificial intelligence assistant and you need to engage in a helpful, detailed, polite conversation with a user."}, {"role": "user", "content": question} ] st.markdown("**Question posée :**") st.write(question) st.markdown("**Réponse IA :**") perform_chat(messages)
9 unmodified lines1011129 unmodified lineswordcloudplotlymatplotlib9 unmodified lines101112139 unmodified lineswordcloudplotlymatplotlib
.gitignore+1
DATA IA RSE Bordeaux Metropole.pngAdded

RECO IA RSE Bordeaux Metropole.pngAdded

app.py+37-5
collaborons.pyAdded+128
data_manager.py+39-1
data_manager_bziiit.py+49-7
documentations.pyAdded+28
entreprises_labellisees.pyAdded+45
inspirezvous.pyAdded+256
labelRSE.py+3-1
localisation.py+1-2
partiesprenantes.pyAdded+156
requirements.txt+1