kawadou commited on
Commit
2b5ccc9
1 Parent(s): 9e89af2

Add application file

Browse files
.streamlit/.env ADDED
@@ -0,0 +1 @@
 
 
1
+ API_TOKEN_PERPLEXITYAI = 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
ActionsRSE.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import data_manager
3
+
4
+ def display_actions_rse():
5
+ # Utilisation de data_manager pour récupérer les données
6
+ data, total_hits = data_manager.get_data()
7
+
8
+ if total_hits > 0:
9
+ # Ajout des titres en haut de l'écran, similaires à organisations_engagees.py mais avec un texte personnalisé
10
+ st.markdown("## OPEN DATA Bordeaux Métropole RSE")
11
+ st.markdown("### Découvrer les actions RSE des organisations engagées de Bordeaux Métropole")
12
+
13
+ secteurs = sorted({record.get("libelle_section_naf") for record in data if record.get("libelle_section_naf")})
14
+ secteur_selectionne = st.selectbox("Filtre par secteur d'activité :", ["Tous"] + secteurs)
15
+
16
+ # Filtrage des actions RSE basé uniquement sur le secteur sélectionné
17
+ actions_filtrees = [
18
+ record for record in data
19
+ if record.get("libelle_section_naf") == secteur_selectionne or secteur_selectionne == "Tous"
20
+ ]
21
+
22
+ # Affichage des actions RSE filtrées
23
+ if actions_filtrees:
24
+ for action in actions_filtrees:
25
+ # Utilisation de Markdown pour l'affichage enrichi, incluant le gras
26
+ st.markdown(f":green_heart: **Entreprise**: {action.get('nom_courant_denomination')}\n\n**Action**: {action.get('action_rse')}", unsafe_allow_html=True)
27
+ else:
28
+ st.write("Aucune action RSE correspondante trouvée.")
29
+
30
+ # Afficher le total des actions RSE
31
+ st.markdown(f"**Total des actions RSE :** {len(actions_filtrees)}")
32
+
33
+ else:
34
+ st.write("Erreur lors de la récupération des données.")
AnalyseActionsRSE.py ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from ISO26000 import classify_actions_rse_ISO26000 as classify_iso26000
3
+ from impactscore import classify_actions_rse_IMPACTSCORE as classify_impactscore
4
+ from data_manager import get_data
5
+
6
+ criteria = {}
7
+ if "Autres" not in criteria:
8
+ criteria["Autres"] = []
9
+
10
+ company_info = "Some company info"
11
+
12
+ criteria["Autres"].append(company_info)
13
+
14
+ def display_analyse_actions_rse():
15
+ st.markdown("## IA RSE :mag_right:")
16
+ st.markdown("### Classification des actions RSE selon 3 approches :")
17
+
18
+ approach = st.radio(
19
+ "Choisissez l'approche de classification :point_down:",
20
+
21
+ ["Norme ISO 26000", "ODD Objectifs de Développement Durable (en cours de développement)","Impact Score (en cours de développement)"],
22
+ index=0,
23
+ format_func=lambda x: x.split(" :")[0]
24
+ )
25
+
26
+ if approach == "Norme ISO 26000":
27
+ # Récupérer les données depuis data_manager.py
28
+ data, total_hits = get_data()
29
+
30
+ st.markdown("""<hr style='border-color: darkgrey;'>""", unsafe_allow_html=True)
31
+
32
+ st.markdown("""
33
+ :earth_africa: **QU'EST-CE QUE LA NORME ISO 26000 ?**
34
+
35
+ La norme ISO 26000 propose une grille de lecture de la thématique développement durable ultra-pratique pour déployer une politique RSE d'entreprise bien structurée, qui ne laisse rien de côté. Publiée en 2010, cette norme volontaire a été élaborée en concertation avec près de 90 pays à travers le monde, dont la France.
36
+
37
+ **COMMENT EST-ELLE STRUCTURÉE ?**
38
+
39
+ ISO 26000 : Une grille de lecture à 7 entrées
40
+
41
+ - 🏢 La gouvernance de la structure
42
+ - 👨‍👩‍👧‍👦 Les droits humains
43
+ - 🤝 Les conditions et relations de travail
44
+ - 🌱 La responsabilité environnementale
45
+ - ⚖️ La loyauté des pratiques
46
+ - 🛍️ Les questions relatives au consommateur et à la protection du consommateur
47
+ - 🌍 Les communautés et le développement local.
48
+ """)
49
+ st.markdown("""<small>Source AFNOR : <a href="https://www.afnor.org/developpement-durable/demarche-iso-26000/" target="_blank">www.afnor.org/developpement-durable/demarche-iso-26000/</a></small>""", unsafe_allow_html=True)
50
+
51
+ st.markdown("""<hr style='border-color: darkgrey;'>""", unsafe_allow_html=True)
52
+ st.markdown("### Classification des actions RSE selon ISO 26000")
53
+
54
+ pictograms = {
55
+ "Gouvernance de la structure": "🏢",
56
+ "Droits humains": "👨‍👩‍👧‍👦",
57
+ "Conditions et relations de travail": "🤝",
58
+ "Responsabilité environnementale": "🌱",
59
+ "Loyauté des pratiques": "⚖️",
60
+ "Questions relatives au consommateur": "🛍️",
61
+ "Communautés et développement local": "🌍",
62
+ "Autres": "❓"
63
+ }
64
+
65
+ criteria_counts = classify_iso26000(data)
66
+
67
+ total_actions = 0
68
+
69
+ for category, actions in criteria_counts.items():
70
+ if category in pictograms:
71
+ st.subheader(f"{pictograms[category]} {category}")
72
+ else:
73
+ st.subheader(f"{pictograms['Autres']} Autres")
74
+ total_actions += len(actions)
75
+ for action in actions:
76
+ nom_entreprise = action.get('nom_courant_denomination', 'Information non disponible')
77
+ st.write(f"Entreprise : {action.get('name','N/A')}, Action RSE : {action.get('action_rse', 'N/A')}, Activité : {action.get('activity', 'N/A')}, Ville : {action.get('city', 'N/A')}")
78
+
79
+ st.markdown("""<hr style='border-color: darkgrey;'>""", unsafe_allow_html=True)
80
+ st.markdown(f"**Total des actions RSE :** {total_actions}")
81
+
82
+ elif approach == "Impact Score (en cours de développement)":
83
+ # Récupérer les données depuis data_manager.py
84
+ data, total_hits = get_data()
85
+
86
+ st.markdown("""<hr style='border-color: darkgrey;'>""", unsafe_allow_html=True)
87
+
88
+ st.markdown("""
89
+ 🌳 **QU'EST-CE QUE L'IMPACT SCORE ?**
90
+
91
+ Ce référentiel commun et unique a été co-construit par 30 réseaux d’entreprises afin de publier en transparence leurs données d’impact, exigence européenne depuis 2024.
92
+
93
+ **COMMENT EST-IL STRUCTURÉE ?**
94
+
95
+ IMPACT SCORE repose sur 3 piliers essentiels :
96
+
97
+ - 🚫 LIMITATION DES EXTERNALITÉS NÉGATIVES
98
+ - 💡 PARTAGE DU POUVOIR ET DE LA VALEUR
99
+ - 🎯 STRATÉGIE À IMPACT
100
+ """)
101
+
102
+
103
+ st.markdown("""<small>Source MOUVEMENT IMPACT FRANCE : <a href="https://impactscore.fr/comprendre-limpact-score/" target="_blank">https://impactscore.fr/comprendre-limpact-score/</a></small>""", unsafe_allow_html=True)
104
+
105
+ st.markdown("""<hr style='border-color: darkgrey;'>""", unsafe_allow_html=True)
106
+
107
+ criteria_counts = classify_impactscore(data)
108
+
109
+ total_actions = sum([len(actions) for actions in criteria_counts.values()])
110
+ st.markdown(f"**Total des actions RSE :** {total_actions}")
111
+
112
+ ### OBJECTIF DE DEVELOPPEMENT DURABLE ###
113
+ elif approach == "ODD Objectifs de Développement Durable (en cours de développement)":
114
+ # Récupérer les données depuis data_manager.py
115
+ data, total_hits = get_data()
116
+
117
+ st.markdown("""<hr style='border-color: darkgrey;'>""", unsafe_allow_html=True)
118
+
119
+ st.markdown("""
120
+ 🌳 **QU'EST-CE QUE LES 17 ODD ?**
121
+
122
+ Au cœur de l’Agenda 2030, 17 Objectifs de développement durable (ODD) ont été fixés. Ils couvrent l’intégralité des enjeux de développement dans tous les pays tels que le climat, la biodiversité, l’énergie, l’eau, la pauvreté, l’égalité des genres, la prospérité économique ou encore la paix, l’agriculture, l’éducation, etc.
123
+
124
+ **COMMENT SONT-ILS STRUCTURÉS ?**
125
+
126
+ - ODD n°1 - Pas de pauvreté
127
+ - ODD n°2 - Faim « Zéro »
128
+ - ODD n°3 - Bonne santé et bien-être
129
+ - ODD n°4 - Éducation de qualité
130
+ - ODD n°5 - Égalité entre les sexes
131
+ - ODD n°6 - Eau propre et assainissement
132
+ - ODD n°7 - Énergie propre et d'un coût abordable
133
+ - ODD n°8 - Travail décent et croissance économique
134
+ - ODD n°9 - Industrie, innovation et infrastructure
135
+ - ODD n°10 - Inégalités réduites
136
+ - ODD n°11 - Villes et communautés durable
137
+ - ODD n°12 - Consommation et production responsables
138
+ - ODD n°13 - Lutte contre les changements climatiques
139
+ - ODD n°14 - Vie aquatique
140
+ - ODD n°15 - Vie terrestre
141
+ - ODD n°16 - Paix, justice et institutions efficaces
142
+ - ODD n°17 - Partenariats pour la réalisation des objectifs
143
+
144
+ """)
145
+
146
+
147
+ st.markdown("""<small>Source AGENDA 2030 EN FRANCE : <a href="https://www.agenda-2030.fr/17-objectifs-de-developpement-durable/?" target="_blank">https://impactscore.fr/comprendre-limpact-score/</a></small>""", unsafe_allow_html=True)
148
+
149
+ st.markdown("""<hr style='border-color: darkgrey;'>""", unsafe_allow_html=True)
150
+
151
+ criteria_counts = classify_impactscore(data)
152
+
153
+ total_actions = sum([len(actions) for actions in criteria_counts.values()])
154
+ st.markdown(f"**Total des actions RSE :** {total_actions}")
155
+
156
+ if approach == "Norme ISO 26000":
157
+ st.subheader("Synthèse par catégorie ISO 26000")
158
+ synthesis = {category: len(actions) for category, actions in criteria_counts.items()}
159
+ synthesis_sorted = dict(sorted(synthesis.items(), key=lambda item: item[1], reverse=True))
160
+ for category, count in synthesis_sorted.items():
161
+ st.write(f"{category}: {count} action(s) RSE")
162
+
163
+ if __name__ == "__main__":
164
+ display_analyse_actions_rse()
DATA IA RSE Bordeaux Metropole.png ADDED
DATA_bziiit/__init__.py ADDED
File without changes
ISO26000.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from data_manager import get_data
2
+
3
+ def classify_actions_rse_ISO26000(data):
4
+ data, _ = get_data() # Récupérer les données depuis data_manager.py
5
+
6
+ criteria = {
7
+ "Gouvernance de la structure": [],
8
+ "Droits humains": [],
9
+ "Conditions et relations de travail": [],
10
+ "Responsabilité environnementale": [],
11
+ "Loyauté des pratiques": [],
12
+ "Questions relatives au consommateur": [],
13
+ "Communautés et développement local": [],
14
+ "Autres": []
15
+ }
16
+
17
+ # Keywords for each ISO 26000 category to help in classifying the actions
18
+ keywords = {
19
+ "Gouvernance de la structure": ["gouvernance", "structure", "organisation","leadership", "processus décisionnel", "responsabilité", "transparence", "éthique","entreprise à mission", "éthique d'entreprise", "transparence", "gouvernance responsable", "statuts", "loi pacte", "charte éthique","politique RSE dans la durée", "sens à la mission","fresque du climat"],
20
+ "Droits humains": ["droits humains", "droit", "humains","non-discrimination", "libertés fondamentales", "droits civils et politiques", "droits économiques, sociaux et culturels", "groupes vulnérables","humain au centre","lutter contre les discriminations"],
21
+ "Conditions et relations de travail": ["conditions de travail", "relations de travail", "emploi", "emploi et relations employeur-employé", "conditions de travail et protection sociale", "dialogue social", "santé et sécurité au travail", "développement des ressources humaines","télétravail", "semaine de 4 jours", "bien-être", "formation RSE", "sensibilisation RSE", "inclusion sociale", "diversité", "équilibre vie professionnelle", "qualité de vie au travail","inclusion des femmes","centrer sur l'humain","engagement des équipes"],
22
+ "Responsabilité environnementale": ["environnement", "écologie", "durable","prévention de la pollution", "utilisation durable des ressources", "atténuation et adaptation au changement climatique", "protection de l'environnement, de la biodiversité et restauration des habitats naturels","carbone", "véhicules électriques", "plantation d'arbres", "réduction plastique", "compost", "gestion de l'eau", "énergies renouvelables", "réduction émissions", "déchets", "recyclage", "mobilité durable", "transport en commun", "réutilisation", "reconditionné", "panneaux solaires","véhicules électriques","vélo électrique", "mobilité durable","décarbonation","réduction consommation d'eau","véhicules hybrides","véhicules hydrides","consommation d'eau"],
23
+ "Loyauté des pratiques": ["loyauté", "éthique", "pratiques","lutte contre la coruption", "comportement éthique", "concurrence loyale", "promotion de la responsabilité sociale dans la chaîne de valeur", "respect des droits de propriété","pratiques loyales en matière de marketing, d'information et de contrats", "protection de la santé et de la sécurité des consommateurs", "consommation durable", "service et assistance après-vente", "protection et confidentialité des données des consommateurs","commerce équitable", "marketing éthique", "droits des consommateurs", "transparence des informations", "pratiques loyales", "fournisseurs locaux","partenaires de proximité"],
24
+ "Questions relatives au consommateur": ["consommateur", "client", "service","service client", "protection du consommateur", "consommation responsable", "satisfaction client", "qualité des produits et services", "sécurité des produits et services", "information et éducation des consommateurs", "santé et sécurité des consommateurs", "service après-vente", "garantie", "retour produit", "éthique des affaires", "commerce équitable", "marketing éthique", "droits des consommateurs", "transparence des informations", "pratiques loyales"],
25
+ "Communautés et développement local": ["communauté", "développement local", "société","implication de la communauté", "éducation et culture", "création d'emplois et développement des compétences", "développement des technologies", "création de richesse et de revenus","engagement communautaire", "développement local", "actions caritatives", "événements sportifs", "soutien aux associations", "inclusion sociale", "lutte contre les discriminations", "coopération locale", "soutien à l'économie locale","écosystèmes sportifs", "touristiques", "culturels", "1% for the planet","préservation site", "dynamisation communauté","commun sportif", "transmission", "formations"],
26
+
27
+ }
28
+
29
+ for record in data:
30
+ action_rse = record.get("action_rse", "").lower()
31
+ company_info = {
32
+ "name": record.get("nom_courant_denomination", "N/A"),
33
+ "action_rse": action_rse,
34
+ "activity": record.get("libelle_section_naf", "N/A"),
35
+ "city": record.get("commune", "N/A")
36
+ }
37
+ found_category = False
38
+ for criterion, key_phrases in keywords.items():
39
+ if any(key_phrase in action_rse for key_phrase in key_phrases):
40
+ criteria[criterion].append(company_info)
41
+ found_category = True
42
+ break # Assuming each action belongs to one category only
43
+
44
+ # Si l'action n'a pas été classifiée dans une catégorie existante, la placer dans "Autres"
45
+ if not found_category:
46
+ criteria["Autres"].append(company_info)
47
+
48
+ return criteria
ODD.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ from data_manager import get_data
3
+
4
+ def classify_actions_rse_ODD(data):
5
+ data, _ = get_data() # Assuming the function get_data() retrieves the RSE action data
6
+
7
+ # Definition of the 17 SDGs and their associated keywords
8
+ odd_criteria = {
9
+ "ODD 1: No Poverty": ["pauvreté", "précarité", "aide financière"],
10
+ "ODD 2: Zero Hunger": ["faim", "sécurité alimentaire", "nutrition"],
11
+ "ODD 3: Good Health and Well-being": ["santé", "bien-être", "soins médicaux", "vaccination"],
12
+ "ODD 4: Quality Education": ["éducation", "apprentissage", "école", "alphabétisation"],
13
+ "ODD 5: Gender Equality": ["égalité des sexes", "femmes", "droits des femmes"],
14
+ "ODD 6: Clean Water and Sanitation": ["eau propre", "sanitation", "hygiène"],
15
+ "ODD 7: Affordable and Clean Energy": ["énergie renouvelable", "énergie propre", "efficacité énergétique"],
16
+ "ODD 8: Decent Work and Economic Growth": ["emploi", "travail décent", "croissance économique"],
17
+ "ODD 9: Industry, Innovation, and Infrastructure": ["industrie", "innovation", "infrastructure"],
18
+ "ODD 10: Reduced Inequalities": ["inégalités", "justice sociale", "équité"],
19
+ "ODD 11: Sustainable Cities and Communities": ["développement urbain", "communauté durable", "urbanisme"],
20
+ "ODD 12: Responsible Consumption and Production": ["consommation durable", "production durable", "recyclage"],
21
+ "ODD 13: Climate Action": ["climat", "réchauffement global", "émissions"],
22
+ "ODD 14: Life Below Water": ["océans", "mers", "aquatique"],
23
+ "ODD 15: Life on Land": ["terrestre", "biodiversité", "déforestation"],
24
+ "ODD 16: Peace, Justice, and Strong Institutions": ["paix", "justice", "institution"],
25
+ "ODD 17: Partnerships for the Goals": ["partenariat", "coopération internationale", "synergie"]
26
+ }
27
+
28
+ # Initialize dictionary to store classification results
29
+ classified_data = {odd: [] for odd in odd_criteria}
30
+
31
+ # Classify each RSE action based on ODD keywords
32
+ for record in data:
33
+ if 'description' in record:
34
+ description = record['description'].lower()
35
+ for odd, keywords in odd_criteria.items():
36
+ if any(keyword in description for keyword in keywords):
37
+ classified_data[odd].append(record)
38
+
39
+ return classified_data
40
+
41
+ # Example of using the function with some mock data
42
+ data_example = [
43
+ {"description": "L'entreprise fournit une aide financière pour lutter contre la pauvreté."},
44
+ {"description": "Programme de nutrition pour éliminer la faim."},
45
+ {"description": "Nouvelle politique d'emploi pour promouvoir le travail décent et la croissance économique."}
46
+ ]
47
+ classified_results = classify_actions_rse_ODD(data_example)
48
+ print(classified_results)
49
+
50
+
51
+
RAG.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import RagTokenizer, RagRetriever, RagTokenForGeneration
2
+ from datasets import load_dataset
3
+ import torch
4
+ def load_rag_model():
5
+ tokenizer = RagTokenizer.from_pretrained("nklomp/rag-example")
6
+ retriever = RagRetriever.from_pretrained("nklomp/rag-example", dataset=load_dataset("your_dataset"))
7
+ model = RagTokenForGeneration.from_pretrained("nklomp/rag-example", retriever=retriever)
8
+ return tokenizer, model
9
+
10
+ def query_model(tokenizer, model, query):
11
+ inputs = tokenizer(query, return_tensors="pt")
12
+ with torch.no_grad():
13
+ outputs = model.generate(**inputs)
14
+ return tokenizer.decode(outputs[0], skip_special_tokens=True)
15
+
16
+ # Example usage
17
+ tokenizer, model = load_rag_model()
18
+ user_query = "I am looking for companies that can handle a large construction project."
19
+ response = query_model(tokenizer, model, user_query)
20
+ print(response)
21
+
22
+
23
+
24
+
25
+
26
+
27
+
28
+
29
+
30
+
31
+
32
+
33
+
34
+
35
+
36
+
37
+
38
+
RECO IA RSE Bordeaux Metropole.png ADDED
app.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ import os
3
+
4
+ import streamlit as st
5
+ from organisations_engagees import display_organisations_engagees
6
+ from localisation import display_map
7
+ from statistiques import main as display_statistics
8
+ from ActionsRSE import display_actions_rse
9
+ from AnalyseActionsRSE import display_analyse_actions_rse
10
+ from partiesprenantes import display_materiality_partiesprenantes
11
+
12
+ # Import modifiédes fonctions liées aux scripts
13
+ from projetRSE import display_rse_projects
14
+ from labelRSE import display_rse_labels
15
+ from entreprises_labellisees import display_labelled_companies
16
+ from inspirezvous import *
17
+ from collaborons import display_company_selection_for_materiality,display_materiality_matrix
18
+ from documentations import display_documentation
19
+
20
+ def main():
21
+ st.markdown(":point_left: Cliquez pour vous inspirer", unsafe_allow_html=True)
22
+
23
+ st.sidebar.title("OPEN DATA & IA au service de la RSE")
24
+ section_principale = st.sidebar.radio(
25
+ "Choisissez votre section",
26
+ ["Data Bordeaux métropole", "Data bziiit","IA RSE","Documentation"]
27
+ )
28
+
29
+ if section_principale == "Data Bordeaux métropole":
30
+ app_mode = st.sidebar.radio(
31
+ "Choisissez votre sous-section",
32
+ ["Localisations", "Organisations engagées", "Statistiques", "Actions RSE", "Analyse actions RSE"]
33
+ )
34
+ if app_mode == "Localisations":
35
+ display_map()
36
+ elif app_mode == "Organisations engagées":
37
+ display_organisations_engagees()
38
+ elif app_mode == "Statistiques":
39
+ display_statistics()
40
+ elif app_mode == "Actions RSE":
41
+ display_actions_rse()
42
+ elif app_mode == "Analyse actions RSE":
43
+ display_analyse_actions_rse()
44
+
45
+
46
+ elif section_principale == "Data bziiit":
47
+ ia_mode = st.sidebar.radio(
48
+ "Choisissez votre sous-section",
49
+ ["Labels RSE", "Entreprises labellisées", "Fiches entreprises"]
50
+ )
51
+ if ia_mode == "Labels RSE":
52
+ display_rse_labels()
53
+ elif ia_mode == "Entreprises labellisées":
54
+ display_labelled_companies()
55
+ elif ia_mode == "Fiches entreprises":
56
+ data, bziiit_data = fetch_data()
57
+ selected_company = display_company_selection(data)
58
+ display_company_info(data, bziiit_data, selected_company)
59
+
60
+ elif section_principale == "IA RSE":
61
+ ia_mode = st.sidebar.radio(
62
+ "Choisissez votre sous-section",
63
+ ["Parties prenantes", "Matrice de matérialité"]
64
+ )
65
+ if ia_mode == "Parties prenantes":
66
+ data, bziiit_data = fetch_data()
67
+ selected_company = display_company_selection_for_materiality(data)
68
+ if selected_company:
69
+ display_materiality_partiesprenantes(selected_company, data, bziiit_data)
70
+ elif ia_mode == "Matrice de matérialité":
71
+ data, bziiit_data = fetch_data()
72
+ selected_company = display_company_selection_for_materiality(data)
73
+ if selected_company:
74
+ display_materiality_matrix(selected_company, data, bziiit_data)
75
+
76
+
77
+ elif section_principale == "Documentation":
78
+ display_documentation()
79
+
80
+
81
+ # Instructions communes à toutes les sections
82
+ st.sidebar.markdown("---")
83
+ st.sidebar.markdown("Powered by **bziiit IA RSE**")
84
+ st.sidebar.markdown("2024 : Open source en Licence MIT")
85
+ st.sidebar.markdown("[email protected]")
86
+ st.sidebar.markdown("---")
87
+
88
+ if __name__ == "__main__":
89
+ main()
collaborons.py ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from folium import Map, Marker, Icon, Popup
3
+ from streamlit_folium import folium_static
4
+ from data_manager import get_data
5
+ from data_manager_bziiit import *
6
+
7
+ import os
8
+ from dotenv import load_dotenv
9
+ import openai
10
+
11
+ ###############################################################################################
12
+ # PARTIE 0 : Récupération des données API bziiit et Bordeaux Métropole
13
+ ###############################################################################################
14
+
15
+ def fetch_data():
16
+ data, _ = get_data() # Récupération des données de Bordeaux Métropole
17
+ bziiit_data = get_bziiit_data() # Récupération des données de Bziiit
18
+
19
+ return data, bziiit_data
20
+
21
+ ###############################################################################################
22
+ # PARTIE 1 : Le sélecteur d'entreprise
23
+ ###############################################################################################
24
+ def display_company_selection_for_materiality(data):
25
+ # Get a list of all company names
26
+ 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 list
29
+ 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 None
34
+ if selected_company == "Sélectionner l'entreprise engagée à découvrir":
35
+ return None
36
+
37
+ return selected_company # Return the selected company name
38
+
39
+ # Uniformiser les noms de champs
40
+ def normalize_company_name(record):
41
+ # Gère les différences de noms de champs entre les APIs
42
+ 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 CONVERSATION
50
+ ###############################################################################################
51
+
52
+ # chargement du fichier .env
53
+ load_dotenv(".streamlit/.env")
54
+
55
+ def 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=True
65
+ )
66
+
67
+ assistant_response = ""
68
+ for chunk in response_stream:
69
+ assistant_response += chunk.choices[0].delta.content
70
+
71
+ st.write(assistant_response)
72
+
73
+ ###############################################################################################
74
+ # PARTIE 4 : MATRICE DE MATERIALITE
75
+ ###############################################################################################
76
+ def 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=0
82
+ )
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 MATERIALITE
111
+ ###############################################################################################
112
+
113
+ def 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
+
124
+ def 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
+
data_manager.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests
2
+
3
+ # URL de base de l'API bziiit
4
+ def get_data():
5
+ url = "https://opendata.bordeaux-metropole.fr/api/records/1.0/search/?dataset=met_etablissement_rse&q=&rows=100"
6
+ response = requests.get(url)
7
+ if response.status_code == 200:
8
+ data = response.json()
9
+ records = data.get("records", [])
10
+ if records:
11
+ print(records[0]) # Print an example record
12
+ # Ensure every record includes the 'nom_courant_denomination' key
13
+ for record in records:
14
+ if 'nom_courant_denomination' not in record["fields"]:
15
+ record["fields"]['nom_courant_denomination'] = 'Unknown'
16
+ return [record["fields"] for record in records], data.get("nhits", 0)
17
+ else:
18
+ return [], 0
19
+
20
+ """
21
+ Exemple de données récupérées via l'API de Bordeaux Métropole:
22
+
23
+ st.write("Normalized Company Data:", company_data)
24
+
25
+ Normalized Company Data:
26
+
27
+ {
28
+ "point_geo":[
29
+ 0:44.88136729281935
30
+ 1:-0.5145680443292318
31
+ ]
32
+ "tranche_effectif_etab":"Non déclaré"
33
+ "siret":"8,1383E+13"
34
+ "naf_section":"J"
35
+ "code_naf":"6510Z"
36
+ "ban_x_lambert_93":422559.4
37
+ "code_postal":"33310"
38
+ "naf_groupe":"620"
39
+ "libelle_section_naf":"Information et communication"
40
+ "libelle_groupe_naf":"Programmation, conseil et autres activités informatiques"
41
+ "nom_courant_denomination":"bziiit"
42
+ "tranche_effectif_entreprise":"6 à 9 Salariés"
43
+ "commune":"LORMONT"
44
+ "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)"
45
+ "hierarchie_naf":"Information et communication/Programmation, conseil et autres activités informatiques/libelle_naf"
46
+ "adresse_numero_et_voie":"6 Rue du Courant"
47
+ "ban_y_lambert_93":6426418.2
48
+ }
49
+
50
+ """
data_manager_bziiit.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests
2
+ import streamlit as st
3
+
4
+ # URL de base de l'API bziiit
5
+ BASE_URL = "https://bziiitapi-api.azurewebsites.net"
6
+
7
+ # Fonction de récupération des labels
8
+ def get_labels():
9
+ url = f"{BASE_URL}/opendata/labels"
10
+ response = requests.get(url)
11
+ if response.status_code == 200:
12
+ return response.json()["response"]
13
+ else:
14
+ st.error(f"Échec de récupération des labels: {response.text}")
15
+ return []
16
+
17
+ # Fonction de récupération des projets RSE
18
+ def get_rse_projects():
19
+ url = f"{BASE_URL}/opendata/bordeaux-rse/projects"
20
+ response = requests.get(url)
21
+ if response.status_code == 200:
22
+ return response.json()["response"]
23
+ else:
24
+ st.error(f"Échec de récupération des projets RSE: {response.text}")
25
+ return []
26
+
27
+ # Fonction de récupération des entreprises
28
+ def get_engaged_brands():
29
+ url = f"{BASE_URL}/opendata/bordeaux-rse/brands"
30
+ response = requests.get(url)
31
+ if response.status_code == 200:
32
+ return response.json()["response"]
33
+ else:
34
+ st.error(f"Échec de récupération des marques engagées: {response.text}")
35
+ return []
36
+
37
+ # Fonction consolidant les données labels + projets RSE + marques
38
+ def get_bziiit_data():
39
+ labels = get_labels()
40
+ rse_projects = get_rse_projects()
41
+ engaged_brands = get_engaged_brands()
42
+
43
+ bziiit_data = []
44
+
45
+ # Assurez-vous d'utiliser 'name' pour bziiit data et ajoutez une distinction de type
46
+ for label in labels:
47
+ bziiit_data.append({
48
+ 'type': 'label', # Ajout du type
49
+ 'name': label.get('name', 'Unknown'),
50
+ 'description': label.get('description', 'Unknown'),
51
+ 'logo_url': label.get('logo_url', 'Unknown'),
52
+ 'labels': [label] # Stocke l'objet label entier si nécessaire
53
+ })
54
+
55
+ for project in rse_projects:
56
+ bziiit_data.append({
57
+ 'type': 'project', # Ajout du type
58
+ 'name': project.get('name', 'Unknown'),
59
+ 'labels': project.get('labels', []) # Assurez-vous que 'labels' est une liste dans le JSON de réponse
60
+ })
61
+
62
+ for brand in engaged_brands:
63
+ bziiit_data.append({
64
+ 'type': 'brand', # Ajout du type
65
+ 'name': brand.get('name', 'Unknown'),
66
+ 'logo_url': brand.get('logo_url', 'Unknown'), # Assurez-vous que 'logo_url' est une URL valide
67
+ 'description': brand.get('description', 'Unknown'),
68
+ 'labels': brand.get('labels', [])
69
+ })
70
+
71
+ return bziiit_data
documentations.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+
3
+ def display_documentation():
4
+
5
+ st.markdown("<hr style='border-color: darkgrey;'>", unsafe_allow_html=True) # Add this line
6
+
7
+ st.title("OPEN DATA IA RSE Bordeaux Métropole")
8
+ st.markdown("## La Data et l'IA au service des démarches RSE (Economie, Social, Environnemental)")
9
+
10
+ st.image("DATA IA RSE Bordeaux Metropole.png", caption="Data IA RSE Bordeaux Metropole")
11
+ st.image("RECO IA RSE Bordeaux Metropole.png", caption="RECO IA RSE Bordeaux Metropole")
12
+
13
+ # Credits
14
+
15
+ st.markdown("""<hr style='border-color: darkgrey;'>""", unsafe_allow_html=True)
16
+
17
+
18
+ st.markdown("""
19
+ <div class="credits">
20
+ <p>Data Bordeaux Métropole : Licence MIT 2024 </p>
21
+ <p>Data bziiit : Licence MIT 2024</p>
22
+ <p>API IA : Perplexity</p>
23
+ <p>Avril 2004</p>
24
+ </div>
25
+ """, unsafe_allow_html=True)
26
+
27
+ if __name__ == "__main__":
28
+ main()
entreprises_labellisees.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from data_manager_bziiit import get_bziiit_data
3
+
4
+ def display_labelled_companies():
5
+ st.markdown("## Entreprises Labellisées (source OPEN DATA bziiit)")
6
+ st.markdown("### Découvrez les entreprises engagées avec au moins un label RSE")
7
+
8
+ # Récupération des données bziiit
9
+ bziiit_data = get_bziiit_data()
10
+
11
+ # Filtrage des entreprises ayant au moins un label
12
+ labelled_companies = [brand for brand in bziiit_data if brand['type'] == 'brand' and len(brand.get('labels', [])) > 0]
13
+
14
+ # Calcul du nombre de labels par entreprise
15
+ for brand in labelled_companies:
16
+ brand['label_count'] = len(brand['labels'])
17
+
18
+ # Calcul et affichage du nombre et du pourcentage d'entreprises labellisées
19
+ total_companies = len([brand for brand in bziiit_data if brand['type'] == 'brand'])
20
+ labelled_companies_count = len(labelled_companies)
21
+ percentage_labelled = round((labelled_companies_count / total_companies) * 100)
22
+ st.markdown(f"**Nb entreprises labellisées :** {labelled_companies_count} ({percentage_labelled}%)")
23
+
24
+ # Tri des entreprises par le nombre de labels, ordre décroissant
25
+ labelled_companies.sort(key=lambda x: x['label_count'], reverse=True)
26
+
27
+ # Affichage des entreprises
28
+ for i in range(0, len(labelled_companies), 5):
29
+ cols = st.columns(5)
30
+ image_placeholders = [col.empty() for col in cols]
31
+ padding_placeholders = [col.empty() for col in cols]
32
+ text_placeholders = [col.empty() for col in cols]
33
+ for j in range(5):
34
+ if i + j < len(labelled_companies):
35
+ company = labelled_companies[i + j]
36
+ with cols[j]:
37
+ if company['logo_url'] != 'Unknown':
38
+ image_placeholders[j].image(company['logo_url'], width=100)
39
+ padding_placeholders[j].write("") # This will act as padding
40
+ text_placeholders[j].write(company['name'])
41
+ text_placeholders[j].write(f"Nb labels : {company['label_count']}")
42
+
43
+
44
+
45
+
impactscore.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ print("""
2
+ 🌍 QU'EST-CE QUE LA NORME ISO 26000 ?
3
+
4
+ La norme ISO 26000 propose une grille de lecture de la thématique développement durable ultra-pratique pour déployer une politique RSE d'entreprise bien structurée, qui ne laisse rien de côté. Publiée en 2010, cette norme volontaire a été élaborée en concertation avec près de 90 pays à travers le monde, dont la France.
5
+
6
+ COMMENT EST-ELLE STRUCTURÉE ?
7
+
8
+ ISO 26000 : Une grille de lecture à 7 entrées
9
+
10
+ 🏢 La gouvernance de la structure
11
+ 👨‍👩‍👧‍👦 Les droits humains
12
+ 🤝 Les conditions et relations de travail
13
+ 🌱 La responsabilité environnementale
14
+ ⚖️ La loyauté des pratiques
15
+ 🛍️ Les questions relatives au consommateur et à la protection du consommateur
16
+ 🌍 Les communautés et le développement local.
17
+ Source AFNOR : www.afnor.org/developpement-durable/demarche-iso-26000/
18
+ """)
19
+
20
+ from data_manager import get_data
21
+
22
+ def classify_actions_rse_IMPACTSCORE(data):
23
+ data, _ = get_data() # Récupérer les données depuis data_manager.py
24
+
25
+ criteria = {
26
+ "Initiatives pour réduire l'empreinte carbone": [],
27
+ "Amélioration des conditions de travail": [],
28
+ "Promotion du recyclage": [],
29
+ "Autres": []
30
+ }
31
+
32
+ keywords = {
33
+ "Initiatives pour réduire l'empreinte carbone": ["empreinte carbone", "réduction des émissions", "transition énergétique"],
34
+ "Amélioration des conditions de travail": ["conditions de travail", "santé et sécurité au travail", "équilibre vie professionnelle"],
35
+ "Promotion du recyclage": ["recyclage", "gestion des déchets", "économie circulaire"],
36
+ }
37
+
38
+ for record in data:
39
+ action_rse = record.get("action_rse", "").lower()
40
+ company_info = {
41
+ "name": record.get("nom_courant_denomination", "N/A"),
42
+ "action_rse": action_rse,
43
+ "activity": record.get("libelle_section_naf", "N/A"),
44
+ "city": record.get("commune", "N/A")
45
+ }
46
+ found_category = False
47
+ for criterion, key_phrases in keywords.items():
48
+ if any(key_phrase in action_rse for key_phrase in key_phrases):
49
+ criteria[criterion].append(company_info)
50
+ found_category = True
51
+ break # Assuming each action belongs to one category only
52
+
53
+ # Si l'action n'a pas été classifiée dans une catégorie existante, la placer dans "Autres"
54
+ if not found_category:
55
+ criteria["Autres"].append(company_info)
56
+
57
+ return criteria
inspirezvous.py ADDED
@@ -0,0 +1,256 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import re
3
+ from folium import Map, Marker, Icon, Popup
4
+ from streamlit_folium import folium_static
5
+ from data_manager import get_data
6
+ from data_manager_bziiit import *
7
+ from ISO26000 import classify_actions_rse_ISO26000
8
+ from bs4 import BeautifulSoup
9
+ from urllib.parse import urlparse
10
+
11
+ ###############################################################################################
12
+ # PARTIE 0 : Récupération des données API bziiit et Bordeaux Métropole
13
+ ###############################################################################################
14
+
15
+ def fetch_data():
16
+ data, _ = get_data() # Récupération des données de Bordeaux Métropole
17
+ bziiit_data = get_bziiit_data() # Récupération des données de Bziiit
18
+
19
+ return data, bziiit_data
20
+
21
+ ###############################################################################################
22
+ # PARTIE 1 : Le sélecteur d'entreprise
23
+ ###############################################################################################
24
+
25
+ def display_company_selection(data):
26
+ # Get a list of all company names
27
+ companies = sorted(list(set(record['nom_courant_denomination'] for record in data)), key=str.lower)
28
+
29
+ selected_company = st.selectbox('Sélectionnez une entreprise', companies)
30
+ return selected_company # Return the selected company name
31
+
32
+ # Uniformiser les noms de champs
33
+ def normalize_company_name(record):
34
+ # Gère les différences de noms de champs entre les APIs
35
+ if 'nom_courant_denomination' in record:
36
+ return record['nom_courant_denomination'].strip().lower()
37
+ elif 'name' in record:
38
+ return record['name'].strip().lower()
39
+ return 'Unknown'
40
+
41
+ ###############################################################################################
42
+ # PARTIE 2 : AFFICHAGE OPEN DATA BORDEAUX METROPOLE
43
+ ###############################################################################################
44
+
45
+ def display_company_info(data, bziiit_data, selected_company):
46
+ normalized_selected = normalize_company_name({'name': selected_company}) # Assurez-vous que cette fonction normalise correctement comme expliqué dans l'étape 1.
47
+ company_data = next((record for record in data if normalize_company_name(record) == normalized_selected), None)
48
+ bziiit_company_data = next((record for record in bziiit_data if normalize_company_name(record) == normalized_selected), None)
49
+
50
+ classified_data = classify_actions_rse_ISO26000(data)
51
+ # Normalize the company name for comparison
52
+ normalized_selected = normalize_company_name({'name': selected_company})
53
+
54
+ # Find the company in the classified data
55
+ company_category = None
56
+ for category, companies in classified_data.items():
57
+ if any(normalize_company_name(company) == normalized_selected for company in companies):
58
+ company_category = category
59
+ break
60
+
61
+ if bziiit_company_data is None:
62
+ bziiit_company_data = {}
63
+
64
+ st.markdown("""<hr style='border-color: darkgrey;'>""", unsafe_allow_html=True)
65
+
66
+ if company_data:
67
+ st.markdown("### Source OPEN DATA Bordeaux Métropole")
68
+ st.write(f"**Nom de l'entreprise:** {company_data.get('nom_courant_denomination', 'Non disponible')}")
69
+
70
+ col10, col20 = st.columns(2)
71
+
72
+ with col10:
73
+ if 'point_geo' in company_data and len(company_data['point_geo']) == 2:
74
+ lat, lon = company_data['point_geo']
75
+ m = Map(location=[lat, lon], zoom_start=10)
76
+ popup_html = f"""
77
+ <div style="width:300px;">
78
+ <b>{company_data.get('nom_courant_denomination', 'Sans nom')}</b><br><br>
79
+ <b>Action RSE:</b><br>
80
+ {company_data.get('action_rse', 'Non spécifiée')}<br><br>
81
+ <hr style="margin: 1px 0; border: none; border-top: 1px solid #ccc;">
82
+ <b>Secteur d'activité:</b> {company_data.get('libelle_section_naf', 'Non spécifié')}
83
+ </div>
84
+ """
85
+ icon = Icon(icon="leaf", prefix='fa', color='green')
86
+ Marker([lat, lon], icon=icon, popup=Popup(popup_html, max_width=500)).add_to(m)
87
+ folium_static(m, width=330, height=500)
88
+ else:
89
+ st.write("**Position GPS non disponible pour cette entreprise.**")
90
+
91
+ with col20:
92
+ st.write(f"**Nom de l'entreprise :** {company_data.get('nom_courant_denomination', 'Non disponible')}")
93
+ st.write(f"**Commune :** {company_data.get('commune', 'Non disponible')}")
94
+ st.write(f"**Section NAF :** {company_data.get('libelle_section_naf', 'Non disponible')}")
95
+ st.write(f"**Effectif :** {company_data.get('tranche_effectif_entreprise', 'Non spécifié')}")
96
+ action_rse = company_data.get('action_rse', 'Non spécifié')
97
+ st.write(f"**Action RSE :** {action_rse}")
98
+
99
+ if action_rse != 'Non spécifié':
100
+ if company_category:
101
+ st.write(f"**Classification ISO 26000 (via IA) :** {company_category}")
102
+ else:
103
+ st.write("**Classification ISO 26000:** Catégorie non déterminée")
104
+
105
+ else:
106
+ st.error("Aucune donnée disponible pour cette entreprise depuis l'API Bordeaux Métropole.")
107
+
108
+ ###############################################################################################
109
+ # PARTIE 3 : AFFICHAGE OPEN DATA bziiit
110
+ ###############################################################################################
111
+
112
+ def get_labels():
113
+ url = f"{BASE_URL}/opendata/labels"
114
+ response = requests.get(url)
115
+ if response.status_code == 200:
116
+ return response.json()["response"]
117
+ else:
118
+ st.error(f"Échec de récupération des labels: {response.text}")
119
+ return []
120
+
121
+ st.markdown("""<hr style='border-color: darkgrey;'>""", unsafe_allow_html=True)
122
+
123
+
124
+ if bziiit_company_data:
125
+ st.markdown("### Source OPEN DATA bziiit")
126
+
127
+ # Assurez-vous d'avoir les informations nécessaires
128
+ logo_url = bziiit_company_data.get('logo_url', '')
129
+ website_url = bziiit_company_data.get('website_url', '')
130
+
131
+ # Affichez le logo
132
+ if logo_url:
133
+ st.markdown(f'<div style="text-align: center;"><img src="{logo_url}" style="width:120px;" /></div>', unsafe_allow_html=True)
134
+ else:
135
+ st.markdown('<div style="text-align: center;"><em style="font-size: small;">Logo non disponible</em></div>', unsafe_allow_html=True)
136
+
137
+ # Récupérez la description
138
+ description = bziiit_company_data.get('description', '')
139
+
140
+ # Utilisez une regex pour trouver les URL dans la description
141
+ website_url = re.findall(r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', description)
142
+
143
+ # Vérifiez si une URL a été trouvée
144
+ if website_url:
145
+ # Prenez la première URL trouvée
146
+ website_url = website_url[0]
147
+ st.markdown(f'<div style="text-align: center;">[Site web de l\'entreprise]({website_url})</div>', unsafe_allow_html=True)
148
+ else:
149
+ st.markdown('<div style="text-align: center;"><em style="font-size: small;">URL du site web non disponible</em></div>', unsafe_allow_html=True)
150
+
151
+ description_html = bziiit_company_data.get('description', 'Description non disponible')
152
+ description_text = BeautifulSoup(description_html, "html.parser").get_text()
153
+ st.write("📝 **Description de l'entreprise:**")
154
+ st.write(description_text)
155
+
156
+ st.markdown("🏷️ **Labels / Certifications RSE - Qualité :**")
157
+ labels = get_labels() # Get the labels using the get_labels function
158
+ label_data = bziiit_company_data.get('labels', [])
159
+
160
+ if not label_data:
161
+ st.write("Pas de Labels / Certifications RSE - Qualité actuellement.")
162
+
163
+ else:
164
+ # ...
165
+ for i in range(0, len(label_data), 2): # Loop through labels two at a time
166
+ cols = st.columns(2) # Create two columns
167
+ for j in range(2): # Loop through the two labels
168
+ if i + j < len(label_data): # Check if there is a label to process
169
+ label = label_data[i + j]
170
+ label_name = label.get("name", "Label non spécifié")
171
+ # Find the corresponding label in the labels data
172
+ label_info = next((l for l in labels if l.get("name") == label_name), None)
173
+ if label_info: # Only process labels with info
174
+ label_description = label_info.get("description", "Description non disponible") # Get the label description from the label info
175
+ logo_url = label_info.get("logo_url") # Get the logo URL from the label info
176
+ try:
177
+ # Display the image in the corresponding column with a tooltip
178
+ 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)
179
+ except Exception as e:
180
+ st.error(f"Erreur lors de l'affichage de l'image : {e}")
181
+ # ...
182
+ if st.button('Ici pour visualiser le mail à envoyer pour référencer un nouveau label / certification RSE - Qualité'):
183
+ st.markdown("""
184
+ **Objet email :**
185
+ Demande de référencement Certification / Label RSE - Qualité
186
+
187
+ **Corps email :**
188
+ Bonjour,
189
+
190
+ 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
191
+
192
+ URL à renseigner - 01 :
193
+ URL à renseigner - 02 :
194
+ URL à renseigner - 03 :
195
+ ...
196
+
197
+ Nom du demandeur :
198
+ Qualité ou statut :
199
+
200
+ Destinataire : [email protected]
201
+
202
+ Merci par avance de votre aide pour développer la visibilité de vos Labels / Certifications
203
+
204
+ L'équipe OPEN DATA IA RSE Bordeaux Métropole
205
+ """, unsafe_allow_html=True)
206
+
207
+ else:
208
+ st.write("**Aucune donnée bziiit disponible pour cette entreprise.**")
209
+
210
+
211
+ def is_valid_url(url):
212
+ try:
213
+ response = requests.head(url)
214
+ return response.status_code == 200
215
+ except requests.RequestException:
216
+ return False
217
+
218
+
219
+ """
220
+ ###############################################################################################
221
+ # PARTIE 5 : AFFICHAGE INSPIREZ VOUS
222
+ ###############################################################################################
223
+ def display_similar_companies(data, selected_company):
224
+ classified_data = classify_actions_rse_ISO26000(data)
225
+ company_data = next((record for record in data if record['nom_courant_denomination'] == selected_company), None)
226
+ if company_data:
227
+ action_rse = company_data.get('action_rse', 'Unknown').lower()
228
+ for category, companies in classified_data.items():
229
+ if any(company.get('action_rse', 'Unknown').lower() == action_rse for company in companies):
230
+ """
231
+ # st.markdown("""<hr style='border-color: darkgrey;'>""", unsafe_allow_html=True)
232
+ """
233
+ st.write("Ces organisations pourraient également vous inspirer")
234
+ max_pages = (len(companies) - 1) // 5 + 1
235
+ cols = st.columns([1,1,1,1,1])
236
+ if cols[1].button('Précédent'):
237
+ page = max(page - 1, 1)
238
+ page = cols[2].number_input('Page', min_value=1, max_value=max_pages, value=1, step=1)
239
+ if cols[3].button('Suivant'):
240
+ page = min(page + 1, max_pages)
241
+
242
+ companies_to_display = companies[(page - 1) * 5:page * 5]
243
+
244
+ st.write(f"Page: {page}") # Debugging line
245
+ st.write(f"Companies to display: {companies_to_display}") # Debugging line
246
+
247
+ for i, company in enumerate(companies_to_display):
248
+ st.write(f"Company: {company}") # Debugging line
249
+ logo_url = company.get('logo', 'https://opendata.bordeaux-metropole.fr/assets/theme_image/Open%20data%20-%20Pictos%2050px%20x%2050px-03.jpg')
250
+ if is_valid_url(logo_url):
251
+ cols[i].image(logo_url, width=50)
252
+ else:
253
+ cols[i].image('https://opendata.bordeaux-metropole.fr/assets/theme_image/Open%20data%20-%20Pictos%2050px%20x%2050px-03.jpg', width=50)
254
+ cols[i].write(f"**{company.get('name', 'Unknown')}**")
255
+ cols[i].write(f"{company.get('action_rse', 'Unknown')[:30]}")
256
+ """
labelRSE.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from collections import Counter
3
+
4
+ from data_manager import get_data
5
+ from data_manager_bziiit import get_labels, get_engaged_brands
6
+
7
+ def display_rse_labels():
8
+ st.markdown("## OPEN DATA bziiit Labels RSE")
9
+ st.markdown("### Découvrez les labels et certifications (RSE, Qualité...)")
10
+
11
+ labels_option = st.radio(
12
+ "Choisissez les labels à afficher :",
13
+ ("Labels / Certifications des organisations engagées Bdx Métropole", "Tous les labels / Certifications DATA bziiit")
14
+ )
15
+
16
+
17
+ st.markdown("""<hr style='border-color: darkgrey;'>""", unsafe_allow_html=True)
18
+
19
+ labels = get_labels()
20
+
21
+ if labels_option == "Tous les labels / Certifications DATA bziiit":
22
+ labels.sort(key=lambda x: x['name'])
23
+ else:
24
+ # Get the data from Bordeaux Metropole API
25
+ data, _ = get_data()
26
+
27
+ # Get the engaged brands
28
+ engaged_brands = get_engaged_brands()
29
+
30
+ # Get the names of the organizations from Bordeaux Metropole API
31
+ org_names = set(org['nom_courant_denomination'] for org in data if 'nom_courant_denomination' in org)
32
+
33
+ # Filter the engaged brands to include only the organizations in Bordeaux Metropole
34
+ engaged_brands = [brand for brand in engaged_brands if brand['name'] in org_names]
35
+
36
+ # Get the labels used by the organizations
37
+ org_labels = [label['name'] for brand in engaged_brands if 'labels' in brand and brand['labels'] for label in brand['labels']]
38
+
39
+ # Count the labels
40
+ label_counts = Counter(org_labels)
41
+
42
+ # Filter the labels and add the count
43
+ labels = [{'name': label['name'], 'logo_url': label['logo_url'], 'count': label_counts[label['name']]} for label in labels if label['name'] in label_counts]
44
+
45
+ # Sort the labels by count in descending order
46
+ labels.sort(key=lambda x: x['count'], reverse=True)
47
+
48
+ # Display the total number of unique labels
49
+ unique_labels = set(label['name'] for label in labels)
50
+ st.markdown(f"**Nombre de labels / certifications :** {len(unique_labels)}")
51
+
52
+ # Display the labels
53
+ for i in range(0, len(labels), 5):
54
+ cols = st.columns(5)
55
+ for j in range(5):
56
+ if i + j < len(labels):
57
+ label = labels[i + j]
58
+ with cols[j]:
59
+ st.image(label['logo_url'])
60
+ if labels_option == "Tous les labels / Certifications DATA bziiit":
61
+ st.markdown(f'<p style="text-align: center; font-size: 10px;"><a href="{label["website"]}" style="color: darkgray;">Site web</a></p>', unsafe_allow_html=True)
62
+ else:
63
+ st.markdown(f'<p style="text-align: center; font-size: 10px; color: darkgray;">Nb marques certifiées : {label["count"]}</p>', unsafe_allow_html=True)
localisation.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from folium import Map, Marker, Icon, Popup
2
+ from streamlit_folium import folium_static
3
+ import streamlit as st
4
+ from data_manager import get_data
5
+
6
+ def display_map():
7
+ data, total_hits = get_data()
8
+ if data:
9
+ # Ajout des titres en haut de l'écran
10
+ st.markdown("## OPEN DATA Bordeaux Métropole RSE")
11
+ st.markdown("### Localiser les organisations engagées RSE de Bordeaux Métropole")
12
+
13
+ secteurs = sorted({record.get("libelle_section_naf") for record in data if record.get("libelle_section_naf")})
14
+ secteur_selectionne = st.selectbox("Filtre par secteur d'activité :", ["Tous"] + secteurs)
15
+
16
+ if secteur_selectionne != "Tous":
17
+ data = [record for record in data if record.get("libelle_section_naf") == secteur_selectionne]
18
+
19
+ st.markdown("Cliquer sur l'icône pour découvrir l'entreprise et une de ses actions RSE remarquable")
20
+
21
+ m = Map(location=[44.84474, -0.60711], zoom_start=12)
22
+ for item in data:
23
+ try:
24
+ point_geo = item.get('point_geo', [])
25
+ if point_geo:
26
+ lat, lon = float(point_geo[0]), float(point_geo[1])
27
+ if lat and lon:
28
+ popup_html = f"""
29
+ <div style="width:300px;">
30
+ <b>{item.get('nom_courant_denomination', 'Sans nom')}</b><br><br>
31
+ <b>Action RSE:</b><br>
32
+ {item.get('action_rse', 'Non spécifiée')}<br><br>
33
+ <hr style="margin: 1px 0; border: none; border-top: 1px solid #ccc;">
34
+ <b>Secteur d'activité:</b> {item.get('libelle_section_naf', 'Non spécifié')}
35
+ </div>
36
+ """
37
+ popup = Popup(popup_html, max_width=500)
38
+ Marker([lat, lon], popup=popup, icon=Icon(color='green', icon='leaf', prefix='fa')).add_to(m)
39
+ except (ValueError, TypeError, IndexError):
40
+ continue
41
+
42
+ folium_static(m)
43
+
44
+ if __name__ == "__main__":
45
+ display_map()
marquesengagees.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+
2
+ # Dans marquesengagees.py
3
+ import streamlit as st
4
+
5
+ def display_engaged_brands():
6
+ # Exemple de code pour afficher des marques engagées
7
+ st.write("Liste des marques engagées")
organisations_engagees.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ from data_manager import get_data
4
+
5
+ # Fonction pour l'onglet "Organisations engagées"
6
+ def display_organisations_engagees():
7
+ st.markdown("## OPEN DATA Bordeaux Métropole RSE")
8
+ st.markdown("### Découvrez les organisations engagées RSE de Bordeaux Métropole")
9
+
10
+ data, total_hits = get_data()
11
+ if data:
12
+ # Calcul du nombre total d'organisations
13
+ st.markdown(f"Nombre d'organisations : {total_hits}")
14
+
15
+ df = pd.DataFrame(data)
16
+ df = df.rename(columns={
17
+ "nom_courant_denomination": "Nom",
18
+ "commune": "Commune",
19
+ "libelle_section_naf": "Section NAF",
20
+ "tranche_effectif_entreprise": "Effectif",
21
+ "action_rse": "Action RSE"
22
+ })
23
+ df = df[["Nom", "Commune", "Section NAF", "Effectif", "Action RSE"]]
24
+ st.dataframe(df, width=None, height=None)
partiesprenantes.py ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from folium import Map, Marker, Icon, Popup
3
+ from streamlit_folium import folium_static
4
+ from data_manager import get_data
5
+ from data_manager_bziiit import *
6
+
7
+ import os
8
+ from dotenv import load_dotenv
9
+ import openai
10
+
11
+ ###############################################################################################
12
+ # PARTIE 0 : Récupération des données API bziiit et Bordeaux Métropole
13
+ ###############################################################################################
14
+
15
+ def fetch_data():
16
+ data, _ = get_data() # Récupération des données de Bordeaux Métropole
17
+ bziiit_data = get_bziiit_data() # Récupération des données de Bziiit
18
+
19
+ return data, bziiit_data
20
+
21
+ ###############################################################################################
22
+ # PARTIE 1 : Le sélecteur d'entreprise
23
+ ###############################################################################################
24
+ def display_company_selection_for_materiality(data):
25
+ # Get a list of all company names
26
+ 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 list
29
+ 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 None
34
+ if selected_company == "Sélectionner l'entreprise engagée à découvrir":
35
+ return None
36
+
37
+ return selected_company # Return the selected company name
38
+
39
+ # Uniformiser les noms de champs
40
+ def normalize_company_name(record):
41
+ # Gère les différences de noms de champs entre les APIs
42
+ 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 sonar-medium-online + AFFICHAGE DE LA CONVERSATION
50
+ ###############################################################################################
51
+
52
+ # chargement du fichier .env
53
+ load_dotenv(".streamlit/.env")
54
+
55
+ def 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=True
65
+ )
66
+
67
+ assistant_response = ""
68
+ for chunk in response_stream:
69
+ assistant_response += chunk.choices[0].delta.content
70
+
71
+ st.write(assistant_response)
72
+
73
+ ###############################################################################################
74
+ # PARTIE 4 : PARTIES PRENANTES
75
+ ###############################################################################################
76
+ def display_materiality_partiesprenantes(selected_company, data, bziiit_data):
77
+ st.markdown("### Les parties prenantes identifiées par l'IA bziiit / Perplexity - sonar-medium-online")
78
+ option = st.radio(
79
+ "Choisissez une option",
80
+ ('Définition', 'Parties prenantes prioritaires', 'Parties prenantes détaillées'),
81
+ index=0
82
+ )
83
+
84
+ if option == 'Définition':
85
+ st.write("""
86
+ **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 :
87
+
88
+ 1. **Identification des parties prenantes pour une stratégie RSE inclusive**:
89
+ - 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].
90
+ - Cela inclut un large éventail d'acteurs tels que les employés, clients, fournisseurs, actionnaires, communautés locales, ONG et l'État[4][5].
91
+ - 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].
92
+
93
+ 2. **Hiérarchisation et cartographie pour prioriser les actions**:
94
+ - 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].
95
+ - La cartographie des parties prenantes permet de visualiser et de prioriser les relations en fonction de leur importance stratégique pour l'entreprise[2].
96
+ - 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].
97
+
98
+ 3. **Engagement des parties prenantes pour une RSE efficace et crédible**:
99
+ - L'engagement des parties prenantes est fondamental pour construire une démarche RSE crédible et pour obtenir leur soutien[4][5].
100
+ - 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].
101
+ - 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].
102
+
103
+ 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.
104
+
105
+ Citations:
106
+ [1] https://www.greenflex.com/actualites/articles/rse-parties-prenantes/
107
+ [2] https://datavalue-consulting.com/cartographie-partie-prenante-rse/
108
+ [3] https://www.novethic.fr/entreprises-responsables/qui-sont-les-parties-prenantes-de-lentreprise.html
109
+ [4] https://www.cabinetdesaintfront.fr/publications/comment-engager-ses-parties-prenantes/
110
+ [5] https://www.labellucie.com/parties-prenantes-rse
111
+ [6] https://blog.hubspot.fr/marketing/parties-prenantes-rse
112
+ [7] https://www.erudit.org/fr/revues/mi/2013-v17-n2-mi0560/1015400ar/
113
+ [8] https://www.civitime.com/rse/parties-prenantes
114
+ [9] https://speaknact.fr/fr/blog/article/561--impliquer-ses-parties-prenantes-pour-une-rse-efficace
115
+ [10] https://www.abeautifulgreen.com/le-role-des-parties-prenantes-et-la-rse/
116
+ [11] https://www.cairn.info/revue-management-et-avenir-2014-2-page-73.htm
117
+ [12] https://www.squadeasy.com/blog/qui-sont-les-parties-prenantes-dune-entreprise
118
+ [13] https://www.associatheque.fr/fr/fichiers/bao/fiche-memo-RSE-DD-les-etapes-de-la-demarche.pdf
119
+ [14] https://greenly.earth/fr-fr/blog/guide-entreprise/rse-partie-prenantes
120
+ [15] https://www.veolia.com/fr/veolia-group/engagement-rse/engagement-parties-prenantes
121
+
122
+ """)
123
+
124
+
125
+ elif option == 'Parties prenantes prioritaires':
126
+ company_data = next((item for item in data if item['nom_courant_denomination'].strip().lower() == selected_company.strip().lower()), None)
127
+ bziiit_brand_data = next((brand for brand in bziiit_data if brand['type'] == 'brand' and brand['name'].strip().lower() == selected_company.strip().lower()), None)
128
+ if company_data and bziiit_brand_data:
129
+ run_perplexity_chat_parties_prenantes_prioritaires(company_data['nom_courant_denomination'], bziiit_brand_data['description'], company_data['action_rse'])
130
+
131
+
132
+ elif option == 'Parties prenantes détaillées':
133
+ company_data = next((item for item in data if item['nom_courant_denomination'].strip().lower() == selected_company.strip().lower()), None)
134
+ bziiit_brand_data = next((brand for brand in bziiit_data if brand['type'] == 'brand' and brand['name'].strip().lower() == selected_company.strip().lower()), None)
135
+ if company_data and bziiit_brand_data:
136
+ run_perplexity_chat_parties_prenantes_detailed(company_data['nom_courant_denomination'], bziiit_brand_data['description'], company_data['action_rse'])
137
+
138
+ ###############################################################################################
139
+ # PARTIE 5 : FONCTIONS PARTIES PRENANTES
140
+ ###############################################################################################
141
+
142
+ def run_perplexity_chat_parties_prenantes_prioritaires(company_name, company_description, company_rse_action):
143
+ 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."
144
+ messages = [
145
+ {"role": "system", "content": "You are an artificial intelligence assistant and you need to engage in a helpful, detailed, polite conversation with a user."},
146
+ {"role": "user", "content": question}
147
+ ]
148
+ st.markdown("**Question posée :**")
149
+ st.write(question)
150
+ st.markdown("**Réponse IA :**")
151
+ perform_chat(messages)
152
+
153
+ def run_perplexity_chat_parties_prenantes_detailed(company_name, company_description, company_rse_action):
154
+ 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."
155
+ messages = [
156
+ {"role": "system", "content": "You are an artificial intelligence assistant and you need to engage in a helpful, detailed, polite conversation with a user."},
157
+ {"role": "user", "content": question}
158
+ ]
159
+ st.markdown("**Question posée :**")
160
+ st.write(question)
161
+ st.markdown("**Réponse IA :**")
162
+ perform_chat(messages)
163
+
projetRSE.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import re # Importer la bibliothèque pour les expressions régulières
3
+ from data_manager_bziiit import get_rse_projects
4
+
5
+ def remove_html_tags(text):
6
+ """Supprimer les balises HTML d'une chaîne de caractères."""
7
+ clean_text = re.sub('<.*?>', '', text) # Remplacer toute balise HTML par une chaîne vide
8
+ return clean_text
9
+
10
+ def display_rse_projects():
11
+ st.markdown("""
12
+ <style>
13
+ table {
14
+ background-color: inherit !important;
15
+ }
16
+ </style>
17
+ """, unsafe_allow_html=True)
18
+
19
+ st.markdown("## OPEN DATA bziiit Projet RSE")
20
+ st.markdown("### Découvrez tous les projets RSE des marques référencées")
21
+
22
+ projects = get_rse_projects()
23
+ if projects:
24
+ categories = list({project["rse_category"] if project["rse_category"] is not None else "Non catégorisé" for project in projects})
25
+ categories.sort()
26
+ categories.insert(0, 'Toutes')
27
+ selected_category = st.selectbox("Filtre par catégorie RSE", categories, index=0)
28
+
29
+ if selected_category != 'Toutes':
30
+ filtered_projects = [project for project in projects if project["rse_category"] == selected_category or (selected_category == "Non catégorisé" and project["rse_category"] is None)]
31
+ else:
32
+ filtered_projects = projects
33
+
34
+ st.markdown(f"**Nombre de projets :** {len(filtered_projects)}")
35
+
36
+ # Display the projects as thumbnails
37
+ for i in range(0, len(filtered_projects), 5):
38
+ cols = st.columns(5)
39
+ for j in range(5):
40
+ if i + j < len(filtered_projects):
41
+ project = filtered_projects[i + j]
42
+ with cols[j]:
43
+ if project['logo_url']: # Ajouter cette vérification ici
44
+ st.image(project['logo_url'])
45
+ st.markdown(f'<p style="text-align: center;"><b>{project["brand"]["name"]}</b></p>', unsafe_allow_html=True)
46
+ st.markdown(f'<p style="text-align: center;"><b>"{project["name"]}"</b></p>', unsafe_allow_html=True) # Ajouter cette ligne
47
+ st.markdown(f'<p style="text-align: center; font-size: 10px; color: darkgray;">{project["rse_category"] if project["rse_category"] is not None else "Non catégorisé"}</p>', unsafe_allow_html=True)
48
+ st.markdown('<hr style="border-top: 1px dotted lightgray; width:100%;">', unsafe_allow_html=True) # Modifier cette ligne
requirements.txt ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ streamlit
2
+ pandas
3
+ requests
4
+ folium
5
+ streamlit-folium
6
+ transformers
7
+ torch
8
+ torchvision
9
+ torchaudio
10
+ wordcloud
11
+ plotly
12
+ matplotlib
13
+ openai
14
+ beautifulsoup4
statistiques.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import streamlit as st
3
+ import pandas as pd
4
+ import plotly.express as px
5
+ from data_manager import get_data
6
+ from wordcloud import WordCloud, STOPWORDS
7
+ import matplotlib.pyplot as plt
8
+
9
+ def display_companies_by_sector(df):
10
+ sector_counts = df['libelle_section_naf'].value_counts().reset_index()
11
+ sector_counts.columns = ['Secteur', 'Nombre']
12
+ fig = px.bar(sector_counts, x='Secteur', y='Nombre',
13
+ color='Nombre', labels={'Nombre': ''}, template='plotly_white')
14
+ fig.update_layout(xaxis_tickangle=-45, showlegend=False)
15
+ fig.update_traces(showlegend=False)
16
+ st.plotly_chart(fig)
17
+
18
+ def display_company_sizes(df):
19
+ fig = px.histogram(df, x='tranche_effectif_entreprise',
20
+ labels={'tranche_effectif_entreprise':"Taille de l'entreprise", 'count':'Nombre'}, template='plotly_white')
21
+ fig.update_traces(marker_color='green')
22
+ fig.update_layout(yaxis_title="Nombre")
23
+ st.plotly_chart(fig)
24
+
25
+ def display_companies_by_commune(df):
26
+ commune_counts = df['commune'].value_counts(normalize=True).reset_index()
27
+ commune_counts.columns = ['Commune', 'Pourcentage']
28
+ fig = px.pie(commune_counts, values='Pourcentage', names='Commune',
29
+ template='plotly_white', hole=.3)
30
+ fig.update_traces(textinfo='percent+label')
31
+ st.plotly_chart(fig)
32
+
33
+ def display_rse_actions_wordcloud(df):
34
+ st.header("Nuage de mots Actions RSE")
35
+
36
+ custom_stopwords = set(["l", "d", "d ", "des", "qui", "ainsi", "toute", "hors", "plus", "cette", "afin", "via", "d'", "sa", "dans", "ont", "avec", "aux", "ce", "chez", "ont", "cela", "la", "un", "avons", "par", "c'est", "s'est", "aussi", "leurs", "d'un", "nos", "les", "sur", "ses", "tous", "nous", "du", "notre", "de", "et", "est", "pour", "le", "une", "se", "en", "au", "à", "que", "sont", "leur", "son"])
37
+ stopwords = STOPWORDS.union(custom_stopwords)
38
+
39
+ text = " ".join(action for action in df['action_rse'].dropna())
40
+
41
+ wordcloud = WordCloud(stopwords=stopwords, background_color="white", width=800, height=400).generate(text)
42
+
43
+ fig, ax = plt.subplots()
44
+ ax.imshow(wordcloud, interpolation='bilinear')
45
+ ax.axis('off')
46
+ st.pyplot(fig)
47
+
48
+ def main():
49
+ data, _ = get_data()
50
+ df = pd.DataFrame(data)
51
+
52
+ if not df.empty:
53
+ st.markdown("## OPEN DATA Bordeaux Métropole RSE")
54
+ st.markdown("### Statistiques sur les entreprises engagées RSE")
55
+
56
+ st.header("Répartition des entreprises par secteur d'activité")
57
+ display_companies_by_sector(df)
58
+ st.header("Distribution des tailles d'entreprises")
59
+ display_company_sizes(df)
60
+ st.header("Pourcentage d'entreprises par Commune")
61
+ display_companies_by_commune(df)
62
+ display_rse_actions_wordcloud(df)
63
+
64
+ if __name__ == "__main__":
65
+ main()