Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,156 +1,188 @@
|
|
1 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
2 |
import zipfile
|
3 |
import os
|
4 |
-
import
|
5 |
-
import
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
# Function to
|
67 |
-
def
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
#
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
#
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
#
|
147 |
-
|
148 |
-
|
149 |
-
#
|
150 |
-
|
151 |
-
|
152 |
-
|
153 |
-
|
154 |
-
|
155 |
-
#
|
156 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Dernière màj: 2024-10-11
|
2 |
+
|
3 |
+
import streamlit as st
|
4 |
+
from sentence_transformers import SentenceTransformer
|
5 |
+
from sklearn.linear_model import LogisticRegression
|
6 |
+
from sklearn.metrics import balanced_accuracy_score
|
7 |
+
from sklearn.metrics.pairwise import cosine_similarity
|
8 |
+
from sklearn.decomposition import PCA
|
9 |
+
|
10 |
+
import pandas as pd
|
11 |
+
import plotly.express as px # Import plotly express
|
12 |
import zipfile
|
13 |
import os
|
14 |
+
import hashlib
|
15 |
+
import numpy as np
|
16 |
+
|
17 |
+
# Set page configuration
|
18 |
+
st.set_page_config(page_title="Analyse en composantes principales interactive des plongements sémantiques (2 corpus)", layout="wide")
|
19 |
+
|
20 |
+
# Title of the app
|
21 |
+
st.title("Exploration de l'espace sémantique (2 corpus)")
|
22 |
+
|
23 |
+
# Sidebar for uploading files
|
24 |
+
st.sidebar.header("Téléversez vos corpus")
|
25 |
+
uploaded_files = st.sidebar.file_uploader("Téléversez (upload) jusqu'à deux dossiers compressés en format zip", type="zip", accept_multiple_files=True)
|
26 |
+
|
27 |
+
|
28 |
+
# Function to extract texts and labels from zipped folders
|
29 |
+
def load_texts_from_zip(zip_file, corpus_prefix):
|
30 |
+
texts, labels = [], []
|
31 |
+
with zipfile.ZipFile(zip_file, 'r') as zip_ref:
|
32 |
+
for file_info in zip_ref.infolist():
|
33 |
+
if file_info.filename.endswith('.txt'):
|
34 |
+
with zip_ref.open(file_info.filename) as file:
|
35 |
+
text = file.read().decode('utf-8')
|
36 |
+
texts.append(text)
|
37 |
+
labels.append(f'{corpus_prefix}_{os.path.basename(file_info.filename)}')
|
38 |
+
return texts, labels
|
39 |
+
|
40 |
+
|
41 |
+
# Function to compute a hash of the uploaded files for comparison
|
42 |
+
def compute_file_hash(files):
|
43 |
+
file_hash = hashlib.md5()
|
44 |
+
for file in files:
|
45 |
+
file_hash.update(file.read())
|
46 |
+
file.seek(0)
|
47 |
+
return file_hash.hexdigest()
|
48 |
+
|
49 |
+
|
50 |
+
# Function to determine corpus from label prefix
|
51 |
+
def determine_corpus(label, corpus_names):
|
52 |
+
if label.startswith(f'{corpus_names[0]}_'):
|
53 |
+
return corpus_names[0]
|
54 |
+
elif label.startswith(f'{corpus_names[1]}_'):
|
55 |
+
return corpus_names[1]
|
56 |
+
|
57 |
+
|
58 |
+
# Function to process the uploaded files and generate embeddings
|
59 |
+
def process_files_and_generate_embeddings(uploaded_files, model, corpus_names):
|
60 |
+
texts_all, labels_all = [], []
|
61 |
+
for i, zip_file in enumerate(uploaded_files):
|
62 |
+
texts, labels = load_texts_from_zip(zip_file, corpus_names[i])
|
63 |
+
texts_all.extend(texts)
|
64 |
+
labels_all.extend(labels)
|
65 |
+
|
66 |
+
# Generate embeddings
|
67 |
+
embeddings = model.encode(texts_all)
|
68 |
+
|
69 |
+
# Create a DataFrame with embeddings, labels, and corpus information
|
70 |
+
embeddings_df = pd.DataFrame(embeddings)
|
71 |
+
embeddings_df['label'] = labels_all
|
72 |
+
embeddings_df['corpus'] = embeddings_df['label'].apply(determine_corpus, corpus_names=corpus_names)
|
73 |
+
|
74 |
+
return embeddings_df
|
75 |
+
|
76 |
+
# Function to perform PCA on embeddings
|
77 |
+
def perform_pca(embeddings_df, n_components=3):
|
78 |
+
pca = PCA(n_components=n_components)
|
79 |
+
pca_components = pca.fit_transform(embeddings_df.drop(columns=['label', 'corpus']))
|
80 |
+
pca_df = pd.DataFrame(pca_components, columns=[f'PCA{i+1}' for i in range(n_components)])
|
81 |
+
return pd.concat([pca_df, embeddings_df[['label', 'corpus']]], axis=1)
|
82 |
+
|
83 |
+
|
84 |
+
# Function to perform logistic regression on embeddings and compute accuracy
|
85 |
+
def classify_and_report_accuracy(embeddings_df):
|
86 |
+
unique_classes = embeddings_df['corpus'].nunique()
|
87 |
+
|
88 |
+
# Check if there are at least two unique classes for classification
|
89 |
+
if unique_classes < 2:
|
90 |
+
# st.sidebar.write("Classification impossible : il n'y a qu'un seul corpus.")
|
91 |
+
return
|
92 |
+
|
93 |
+
# Proceed with classification if there are at least two classes
|
94 |
+
X = embeddings_df.drop(columns=['label', 'corpus']) # Use full embeddings
|
95 |
+
y_gold = embeddings_df['corpus']
|
96 |
+
|
97 |
+
# Train logistic regression model
|
98 |
+
classifier = LogisticRegression(max_iter=1000)
|
99 |
+
classifier.fit(X, y_gold)
|
100 |
+
|
101 |
+
# Make predictions and compute accuracy
|
102 |
+
y_pred = classifier.predict(X)
|
103 |
+
balanced_acc = balanced_accuracy_score(y_gold, y_pred)
|
104 |
+
st.sidebar.write(f"Classification (précision) : {balanced_acc:.2f}")
|
105 |
+
|
106 |
+
|
107 |
+
# Function to plot embeddings using Plotly (with 2D or 3D switch)
|
108 |
+
def plot_embeddings(pca_df):
|
109 |
+
# Add a checkbox for selecting 3D plot (2D by default)
|
110 |
+
show_3d = st.checkbox("Afficher en 3D", value=False)
|
111 |
+
|
112 |
+
if show_3d:
|
113 |
+
# Plot in 3D using PCA components
|
114 |
+
fig = px.scatter_3d(
|
115 |
+
pca_df, x='PCA1', y='PCA2', z='PCA3',
|
116 |
+
color='corpus', hover_data=['label'],
|
117 |
+
title='Visualisation des Embeddings (3D - PCA)'
|
118 |
+
)
|
119 |
+
else:
|
120 |
+
# Plot in 2D using the first two PCA components
|
121 |
+
fig = px.scatter(
|
122 |
+
pca_df, x='PCA1', y='PCA2', color='corpus', hover_data=['label'],
|
123 |
+
title='Visualisation des Embeddings (2D - PCA)'
|
124 |
+
)
|
125 |
+
|
126 |
+
# Update layout and display the plot
|
127 |
+
fig.update_layout(width=1200, height=800, margin=dict(l=20, r=20, t=50, b=20))
|
128 |
+
st.plotly_chart(fig, use_container_width=True)
|
129 |
+
|
130 |
+
|
131 |
+
|
132 |
+
# Function to compute cosine similarity between two corpora
|
133 |
+
def compute_corpus_similarity(embeddings_df, corpus_names):
|
134 |
+
unique_classes = embeddings_df['corpus'].nunique()
|
135 |
+
|
136 |
+
# Check if there are at least two unique classes for similarity computation
|
137 |
+
if unique_classes < 2:
|
138 |
+
# st.sidebar.write("Calcul de similarité impossible : il n'y a qu'un seul corpus.")
|
139 |
+
return
|
140 |
+
|
141 |
+
# Proceed with cosine similarity calculation
|
142 |
+
corpus_embeddings = embeddings_df.drop(columns=['label', 'corpus'])
|
143 |
+
|
144 |
+
# Compute mean embeddings for each corpus
|
145 |
+
corpus1_embeddings = corpus_embeddings[embeddings_df['corpus'] == corpus_names[0]].values
|
146 |
+
corpus2_embeddings = corpus_embeddings[embeddings_df['corpus'] == corpus_names[1]].values
|
147 |
+
|
148 |
+
similarity = cosine_similarity(corpus1_embeddings, corpus2_embeddings)[0][0]
|
149 |
+
|
150 |
+
# Display cosine similarity
|
151 |
+
st.sidebar.write(f"Similarité Cosine entre les deux corpus: {similarity:.2f}")
|
152 |
+
|
153 |
+
|
154 |
+
# Main logic of the app
|
155 |
+
if uploaded_files and len(uploaded_files) <= 2:
|
156 |
+
# Get the corpus names without the .zip extension
|
157 |
+
corpus_names = [os.path.splitext(uploaded_file.name)[0] for uploaded_file in uploaded_files]
|
158 |
+
|
159 |
+
# Hash uploaded files and reset state if needed
|
160 |
+
file_hash = compute_file_hash(uploaded_files)
|
161 |
+
if 'uploaded_file_hash' not in st.session_state or st.session_state.uploaded_file_hash != file_hash:
|
162 |
+
st.session_state.uploaded_file_hash = file_hash
|
163 |
+
st.session_state.embeddings_df = None
|
164 |
+
|
165 |
+
# Load model
|
166 |
+
if 'model' not in st.session_state:
|
167 |
+
st.session_state.model = SentenceTransformer('distiluse-base-multilingual-cased-v2')
|
168 |
+
|
169 |
+
# Process files and generate embeddings if they aren't already cached
|
170 |
+
if st.session_state.embeddings_df is None:
|
171 |
+
st.session_state.embeddings_df = process_files_and_generate_embeddings(uploaded_files, st.session_state.model, corpus_names)
|
172 |
+
|
173 |
+
embeddings_df = st.session_state.embeddings_df
|
174 |
+
|
175 |
+
# Get the PCA components
|
176 |
+
pca_df = perform_pca(embeddings_df)
|
177 |
+
|
178 |
+
# Perform classification and report accuracy
|
179 |
+
classify_and_report_accuracy(embeddings_df)
|
180 |
+
|
181 |
+
# Compute and display cosine similarity between corpora
|
182 |
+
compute_corpus_similarity(embeddings_df, corpus_names)
|
183 |
+
|
184 |
+
# plot embeddings
|
185 |
+
plot_embeddings(pca_df)
|
186 |
+
|
187 |
+
else:
|
188 |
+
st.warning("Veuillez téléverser 2 corpus sous forme de dossier compressé (.zip) de fichiers texte (.txt).")
|