Spaces:
Running
Running
File size: 10,459 Bytes
c35c8d0 | 1 2 3 4 5 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 67 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 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 | """Analyse lexicale des vidéos retenues. Les comptages portent sur le nombre de VIDÉOS
contenant un terme : un mot répété dix fois dans une description ne compte qu'une fois."""
import re
import unicodedata
from collections import Counter
from itertools import combinations
import numpy as np
import plotly.graph_objects as go
SOURCES = {
"Titres": ("Title",),
"Titres + tags": ("Title", "Tags"),
"Titres + tags + descriptions": ("Title", "Tags", "Description"),
}
STOPWORDS_TEXT = """
au aux avec ce ces cet cette dans de des du elle elles en et eux il ils je la le les leur leurs lui
ma mais me même mes moi mon ne nos notre nous on ou où par pas pour qu que quel quelle quels quelles
qui sa se ses son sur ta te tes toi ton tu un une vos votre vous y à a ai as avons avez ont est es
sommes êtes sont été être était étaient sera seront serait avoir avait avaient aura fait faire fais
font plus moins très trop aussi comme comment pourquoi quand alors donc car ni si tout toute tous
toutes autre autres entre vers chez sans sous après avant depuis pendant contre ici là oui non bien
peu peut peuvent va vont dit ça cela celui celle ceux dont lors ainsi encore déjà
the a an and or of to in on for with at by from is are was were be been this that these those it its
as we you they he she our your their my me not but so if how what why when who which will can do
does did has have had about into over more most all new
video videos vidéo vidéos youtube chaîne chaine channel abonnez abonner abonnement subscribe like
likes follow suivez retrouvez partagez commentaire commentaires lien liens www http https com fr
org net instagram facebook twitter tiktok linkedin shorts short
"""
def fold(word):
"""Clé de comparaison : minuscules sans accents."""
text = unicodedata.normalize("NFKD", word.casefold())
return "".join(c for c in text if not unicodedata.combining(c))
STOPWORDS = {fold(w) for w in STOPWORDS_TEXT.split()}
def segments(text):
"""Découpe en segments (ponctuation, lignes, virgules entre tags), puis en mots.
Les liens, adresses e-mail et @mentions sont retirés."""
text = unicodedata.normalize("NFC", str(text or "")).casefold()
text = re.sub(r"https?://\S+|www\.\S+|\S*@\S+", " | ", text)
# élisions : l'université -> université (aujourd'hui reste intact)
text = re.sub(r"\b(?:qu|jusqu|lorsqu|puisqu|[cdjlmnst])['’]", "", text)
for part in re.split(r"[.,;:!?|/()\[\]{}\"«»\n\r\t•–—]+", text):
yield re.findall(r"[^\W_]+(?:['’][^\W_]+)*", part)
def analyse(df, source, extra_stopwords, query_terms, hide_query):
"""Renvoie (termes par vidéo, libellés affichés)."""
banned = set(STOPWORDS)
ignored = list(extra_stopwords) + (list(query_terms) if hide_query else [])
for expression in ignored:
words = [fold(w) for part in segments(expression.replace("-", " ")) for w in part]
banned.update(words)
banned.add("".join(words)) # #SorbonneNouvelle
def valid(word):
return len(word) > 2 and not word.isdigit() and fold(word) not in banned
documents, forms = [], {}
for _, row in df.iterrows():
found = set()
for column in SOURCES[source]:
for words in segments(row[column]):
# Une expression = deux mots réellement voisins, tous deux conservés
grams = [(w,) for w in words if valid(w)]
grams += [(a, b) for a, b in zip(words, words[1:])
if valid(a) and valid(b) and a != b]
for gram in grams:
key = " ".join(map(fold, gram))
forms.setdefault(key, Counter())[" ".join(gram)] += 1
found.add(key)
documents.append(found)
# Forme affichée : la graphie la plus fréquente (accents conservés)
labels = {k: min(c, key=lambda f: (-c[f], f)) for k, c in forms.items()}
return documents, labels
def top_terms(documents, size, limit):
"""Termes de `size` mots, classés par nombre de vidéos (au moins 2)."""
counts = Counter(t for doc in documents for t in doc if t.count(" ") == size - 1)
ranked = sorted(counts.items(), key=lambda kv: (-kv[1], kv[0]))
return [(t, n) for t, n in ranked if n >= 2][:limit]
def cooccurrences(documents, words, limit=40):
"""Paires de mots présents dans au moins 2 mêmes vidéos."""
wanted = set(words)
pairs = Counter(p for doc in documents for p in combinations(sorted(doc & wanted), 2))
ranked = sorted(pairs.items(), key=lambda kv: (-kv[1], kv[0]))
return [(p, n) for p, n in ranked if n >= 2][:limit]
def layout(nodes, edges, iterations=200):
"""Placement par forces (Fruchterman-Reingold), déterministe."""
n = len(nodes)
angles = np.linspace(0, 2 * np.pi, n, endpoint=False)
pos = np.column_stack([np.cos(angles), np.sin(angles)])
index = {w: i for i, w in enumerate(nodes)}
weights = np.zeros((n, n))
top = max((c for _, c in edges), default=1)
for (a, b), c in edges:
weights[index[a], index[b]] = weights[index[b], index[a]] = c / top
k = 1 / np.sqrt(max(n, 1))
for step in range(iterations):
delta = pos[:, None, :] - pos[None, :, :]
dist = np.maximum(np.linalg.norm(delta, axis=2), 0.01)
force = k * k / dist ** 2 - weights * dist / k
move = (delta * force[:, :, None]).sum(axis=1) - 0.05 * pos
length = np.maximum(np.linalg.norm(move, axis=1), 1e-9)
temp = 0.1 * (1 - step / iterations)
pos += move / length[:, None] * np.minimum(length, temp)[:, None]
return pos
# ---------- Figures ----------
def empty_figure(message):
fig = go.Figure()
fig.update_layout(template="plotly_white", height=300, title=message,
xaxis=dict(visible=False), yaxis=dict(visible=False))
return fig
def plot_terms(documents, labels):
words, pairs = top_terms(documents, 1, 20), top_terms(documents, 2, 20)
if not words:
return empty_figure("Aucun mot présent dans au moins 2 vidéos")
fig = go.Figure()
for items, name, color, visible in ((words, "Mots", "#7c3aed", True),
(pairs, "Expressions de 2 mots", "#0f766e", False)):
fig.add_trace(go.Bar(
x=[n for _, n in items], y=[labels[t] for t, _ in items], orientation="h",
name=name, marker_color=color, visible=visible,
hovertemplate="%{y} : %{x} vidéo(s)<extra></extra>"))
buttons = [dict(label=label, method="update", args=[{"visible": shown}])
for label, shown in (("Mots", [True, False]),
("Expressions de 2 mots", [False, True]))]
fig.update_layout(
title="Termes les plus partagés (nombre de vidéos)", template="plotly_white",
height=650, showlegend=False, xaxis_title="Vidéos",
yaxis=dict(autorange="reversed", automargin=True),
updatemenus=[dict(type="buttons", direction="right", buttons=buttons,
x=1, xanchor="right", y=1.08)])
return fig
def plot_evolution(documents, labels, dates):
words = [t for t, _ in top_terms(documents, 1, 15)]
if not words:
return empty_figure("Pas assez de texte pour suivre une évolution")
span = (dates.max() - dates.min()).days
freq, unit, fmt = (("Y", "année", "%Y") if span > 730 else
("M", "mois", "%m/%Y") if span > 60 else ("D", "jour", "%d/%m/%Y"))
periods = dates.dt.to_period(freq).tolist()
columns = sorted(set(periods)) # seules les périodes avec des vidéos
totals = [periods.count(p) for p in columns]
values = [[sum(w in d for d, q in zip(documents, periods) if q == p) for p in columns]
for w in words]
names = [p.start_time.strftime(fmt) for p in columns]
hover = [[f"{labels[w]} · {name}<br>{v} vidéo(s) sur {total}"
for v, name, total in zip(row, names, totals)] for w, row in zip(words, values)]
fig = go.Figure(go.Heatmap(
z=values, x=names, y=[labels[w] for w in words], hovertext=hover, hoverinfo="text",
colorscale="Purples", zmin=0, colorbar=dict(title="Vidéos")))
fig.update_layout(
title=f"Évolution des mots par {unit} (périodes sans vidéo non affichées)",
template="plotly_white", height=550, xaxis=dict(type="category"),
yaxis=dict(autorange="reversed", automargin=True))
return fig
def plot_network(documents, labels):
candidates = [t for t, _ in top_terms(documents, 1, 25)]
edges = cooccurrences(documents, candidates)
if not edges:
return empty_figure("Aucune paire de mots présente dans au moins 2 vidéos")
nodes = [w for w in candidates if any(w in pair for pair, _ in edges)]
pos = dict(zip(nodes, layout(nodes, edges).tolist()))
counts = {w: sum(w in d for d in documents) for w in nodes}
biggest, strongest = max(counts.values()), max(c for _, c in edges)
fig = go.Figure()
for (a, b), c in edges:
fig.add_trace(go.Scatter(
x=[pos[a][0], pos[b][0]], y=[pos[a][1], pos[b][1]], mode="lines",
line=dict(width=1 + 5 * c / strongest, color="rgba(124,58,237,0.25)"),
hoverinfo="skip"))
hover = []
for w in nodes:
links = [f"{labels[b if a == w else a]} : {c}" for (a, b), c in edges if w in (a, b)]
hover.append(f"<b>{labels[w]}</b> : {counts[w]} vidéo(s)<br>Associé à :<br>"
+ "<br>".join(links[:8]))
fig.add_trace(go.Scatter(
x=[pos[w][0] for w in nodes], y=[pos[w][1] for w in nodes], mode="markers+text",
text=[labels[w] for w in nodes], textposition="top center",
hovertext=hover, hoverinfo="text",
marker=dict(size=[12 + 28 * counts[w] / biggest for w in nodes], color="#7c3aed")))
fig.update_layout(
title="Réseau des mots présents dans les mêmes vidéos", template="plotly_white",
height=650, showlegend=False, hovermode="closest",
xaxis=dict(visible=False), yaxis=dict(visible=False))
return fig
def text_figures(df, source, extra_stopwords, query_terms, hide_query):
documents, labels = analyse(df, source, extra_stopwords, query_terms, hide_query)
return (plot_terms(documents, labels),
plot_evolution(documents, labels, df["Published"]),
plot_network(documents, labels)) |