Spaces:
Running
Running
Download text_analysis.py from clementBE/Youtube_osint: direct link, hf CLI and curl.
- Browser
- Download file 10.5 kB
-
https://huggingface.co/spaces/clementBE/Youtube_osint/resolve/main/text_analysis.py
- Command line
-
hf download hf://spaces/clementBE/Youtube_osint/text_analysis.py
-
curl -L -o text_analysis.py https://huggingface.co/spaces/clementBE/Youtube_osint/resolve/main/text_analysis.py
10.5 kB
| """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)) |