cheikhaidev-ui Claude Sonnet 4.6 commited on
Commit
6a855ca
·
0 Parent(s):

Initial commit : structure et implémentation complète de LinguaScope

Browse files

- app.py : interface Gradio (analyse sentiment + discours FR/EN)
- src/sentiment.py : TextBlob FR (textblob-fr) + EN, détection langue
- src/speech.py : mots parasites, structure discours, score clarté
- src/feedback.py : générateur de feedback Markdown structuré
- src/utils.py : nettoyage texte, tokenisation, TTR, mots parasites
- data/sample_reviews.csv : squelette CSV (text, language, label)
- requirements.txt, .gitignore, README.md

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

Files changed (10) hide show
  1. .gitignore +12 -0
  2. README.md +3 -0
  3. app.py +171 -0
  4. data/sample_reviews.csv +1 -0
  5. requirements.txt +4 -0
  6. src/__init__.py +0 -0
  7. src/feedback.py +198 -0
  8. src/sentiment.py +57 -0
  9. src/speech.py +152 -0
  10. src/utils.py +117 -0
.gitignore ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __pycache__/
2
+ *.py[cod]
3
+ *.pyo
4
+ .env
5
+ venv/
6
+ .venv/
7
+ *.egg-info/
8
+ dist/
9
+ build/
10
+ .DS_Store
11
+ *.log
12
+ *.err
README.md ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ # LinguaScope
2
+
3
+ > Analyse de sentiment et de discours multilingue (FR + EN).
app.py ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # app.py — Point d'entrée Gradio pour LinguaScope
2
+
3
+ import gradio as gr
4
+ from src import sentiment as sentiment_mod
5
+ from src import speech as speech_mod
6
+ from src import feedback as feedback_mod
7
+
8
+ # ---------------------------------------------------------------------------
9
+ # Logique métier
10
+ # ---------------------------------------------------------------------------
11
+
12
+ LANG_MAP = {"Détection auto": None, "Français": "fr", "Anglais": "en"}
13
+
14
+
15
+ def run_analysis(text: str, lang_choice: str) -> tuple[str, str, str, str, str]:
16
+ """
17
+ Orchestre les trois modules et retourne 5 chaînes Markdown
18
+ pour les 5 composants de sortie Gradio.
19
+ """
20
+ if not text or not text.strip():
21
+ empty = "_Entrez un texte pour lancer l'analyse._"
22
+ return empty, empty, empty, empty, empty
23
+
24
+ lang = LANG_MAP.get(lang_choice)
25
+
26
+ sent = sentiment_mod.analyze(text, lang=lang)
27
+ spch = speech_mod.analyze(text, lang=sent["language"] if lang is None else lang)
28
+ fb = feedback_mod.generate(sent, spch)
29
+
30
+ return (
31
+ _render_summary(fb["summary"], sent),
32
+ _render_sentiment(fb["sentiment"], sent),
33
+ _render_speech(fb, spch),
34
+ _render_structure(fb["structure"], spch),
35
+ _render_clarity(fb["clarity"], spch),
36
+ )
37
+
38
+
39
+ # ---------------------------------------------------------------------------
40
+ # Rendus Markdown
41
+ # ---------------------------------------------------------------------------
42
+
43
+ def _render_summary(summary: str, sent: dict) -> str:
44
+ lang_label = {"fr": "Français", "en": "Anglais"}.get(sent["language"], "Inconnu")
45
+ polarity = sent["polarity"]
46
+ bar = _polarity_bar(polarity)
47
+ return (
48
+ f"### Synthèse\n"
49
+ f"{summary}\n\n"
50
+ f"**Langue détectée :** {lang_label}\n\n"
51
+ f"**Polarité** `{polarity:+.4f}`\n\n{bar}"
52
+ )
53
+
54
+
55
+ def _render_sentiment(lines: list[str], sent: dict) -> str:
56
+ body = "\n\n".join(lines)
57
+ sub = sent.get("subjectivity")
58
+ sub_line = f"\n\n**Subjectivité :** `{sub:.0%}`" if sub is not None else ""
59
+ return f"### Sentiment\n{body}{sub_line}"
60
+
61
+
62
+ def _render_speech(fb: dict, spch: dict) -> str:
63
+ wc = spch["word_count"]
64
+ sc = spch["sentence_count"]
65
+ fillers = "\n\n".join(fb["fillers"])
66
+ return (
67
+ f"### Mots parasites\n"
68
+ f"**{wc} mots** · **{sc} phrases**\n\n"
69
+ f"{fillers}"
70
+ )
71
+
72
+
73
+ def _render_structure(lines: list[str], spch: dict) -> str:
74
+ s = spch["structure"]
75
+ checks = (
76
+ f"{'✅' if s['has_intro'] else '❌'} Introduction "
77
+ f"{'✅' if s['has_body'] else '❌'} Développement "
78
+ f"{'✅' if s['has_conclusion'] else '❌'} Conclusion"
79
+ )
80
+ body = "\n\n".join(lines)
81
+ return f"### Structure\n{checks}\n\n{body}"
82
+
83
+
84
+ def _render_clarity(lines: list[str], spch: dict) -> str:
85
+ c = spch["clarity"]
86
+ score = c["clarity_score"]
87
+ bar = _score_bar(score)
88
+ body = "\n\n".join(lines)
89
+ return f"### Clarté\n{bar}\n\n{body}"
90
+
91
+
92
+ def _polarity_bar(polarity: float) -> str:
93
+ """Barre textuelle [-1 … +1] avec curseur."""
94
+ pos = int((polarity + 1) / 2 * 20)
95
+ pos = max(0, min(20, pos))
96
+ bar = "─" * pos + "●" + "─" * (20 - pos)
97
+ return f"`−1 {bar} +1`"
98
+
99
+
100
+ def _score_bar(score: int) -> str:
101
+ """Barre de progression 0-100."""
102
+ filled = int(score / 100 * 20)
103
+ bar = "█" * filled + "░" * (20 - filled)
104
+ return f"`{bar}` **{score}/100**"
105
+
106
+
107
+ # ---------------------------------------------------------------------------
108
+ # Interface Gradio
109
+ # ---------------------------------------------------------------------------
110
+
111
+ EXAMPLE_FR = (
112
+ "Pour commencer, je voudrais aborder la question de l'environnement. "
113
+ "Euh, donc, du coup, il est, euh, vraiment essentiel de réduire nos émissions. "
114
+ "Les énergies renouvelables offrent une alternative viable et durable. "
115
+ "En conclusion, agir maintenant est absolument indispensable pour les générations futures."
116
+ )
117
+
118
+ EXAMPLE_EN = (
119
+ "First, I would like to talk about climate change. "
120
+ "So, like, you know, it's basically the most pressing issue of our time. "
121
+ "Renewable energy is a viable and sustainable alternative. "
122
+ "In conclusion, we must act now to protect future generations."
123
+ )
124
+
125
+ with gr.Blocks(title="LinguaScope") as demo:
126
+
127
+ gr.Markdown("# LinguaScope\nAnalyse de sentiment et de discours — FR & EN")
128
+
129
+ with gr.Row():
130
+ with gr.Column(scale=2):
131
+ text_input = gr.Textbox(
132
+ label="Texte à analyser",
133
+ placeholder="Collez ou tapez votre discours ici…",
134
+ lines=8,
135
+ )
136
+ lang_radio = gr.Radio(
137
+ choices=list(LANG_MAP.keys()),
138
+ value="Détection auto",
139
+ label="Langue",
140
+ )
141
+ with gr.Row():
142
+ submit_btn = gr.Button("Analyser", variant="primary")
143
+ clear_btn = gr.Button("Effacer")
144
+
145
+ gr.Examples(
146
+ examples=[[EXAMPLE_FR, "Français"], [EXAMPLE_EN, "Anglais"]],
147
+ inputs=[text_input, lang_radio],
148
+ label="Exemples",
149
+ )
150
+
151
+ with gr.Column(scale=3):
152
+ out_summary = gr.Markdown()
153
+ with gr.Row():
154
+ out_sentiment = gr.Markdown()
155
+ out_speech = gr.Markdown()
156
+ with gr.Row():
157
+ out_structure = gr.Markdown()
158
+ out_clarity = gr.Markdown()
159
+
160
+ outputs = [out_summary, out_sentiment, out_speech, out_structure, out_clarity]
161
+
162
+ submit_btn.click(fn=run_analysis, inputs=[text_input, lang_radio], outputs=outputs)
163
+ text_input.submit(fn=run_analysis, inputs=[text_input, lang_radio], outputs=outputs)
164
+ clear_btn.click(
165
+ fn=lambda: ("", "Détection auto") + ("",) * 5,
166
+ outputs=[text_input, lang_radio] + outputs,
167
+ )
168
+
169
+
170
+ if __name__ == "__main__":
171
+ demo.launch(theme=gr.themes.Soft())
data/sample_reviews.csv ADDED
@@ -0,0 +1 @@
 
 
1
+ text,language,label
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ gradio
2
+ textblob
3
+ textblob-fr
4
+ langdetect
src/__init__.py ADDED
File without changes
src/feedback.py ADDED
@@ -0,0 +1,198 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # feedback.py — Générateur de feedback
2
+
3
+ from __future__ import annotations
4
+
5
+ # ---------------------------------------------------------------------------
6
+ # Feedback sentiment
7
+ # ---------------------------------------------------------------------------
8
+
9
+ def _feedback_sentiment(sentiment: dict) -> list[str]:
10
+ lines = []
11
+ label = sentiment.get("label", "neutre")
12
+ polarity = sentiment.get("polarity", 0.0)
13
+ subjectivity = sentiment.get("subjectivity")
14
+ lang = sentiment.get("language", "fr")
15
+
16
+ if label == "positif":
17
+ lines.append(f"Le ton général est **positif** (polarité : {polarity:+.2f}).")
18
+ elif label == "négatif":
19
+ lines.append(f"Le ton général est **négatif** (polarité : {polarity:+.2f}).")
20
+ else:
21
+ lines.append(f"Le ton général est **neutre** (polarité : {polarity:+.2f}).")
22
+
23
+ if subjectivity is not None:
24
+ if subjectivity > 0.6:
25
+ lines.append("Le texte est très **subjectif** : il reflète davantage une opinion personnelle qu'un propos factuel.")
26
+ elif subjectivity < 0.3:
27
+ lines.append("Le texte est très **objectif** : le propos s'appuie sur des faits.")
28
+ else:
29
+ lines.append(f"Le niveau de subjectivité est modéré ({subjectivity:.0%}).")
30
+
31
+ return lines
32
+
33
+
34
+ # ---------------------------------------------------------------------------
35
+ # Feedback mots parasites
36
+ # ---------------------------------------------------------------------------
37
+
38
+ def _feedback_fillers(speech: dict) -> list[str]:
39
+ lines = []
40
+ fillers = speech.get("filler_words", {})
41
+ filler_ratio = speech.get("filler_ratio", 0.0)
42
+ warning = speech.get("filler_warning", False)
43
+
44
+ if not fillers:
45
+ lines.append("Aucun mot parasite détecté. Bravo !")
46
+ return lines
47
+
48
+ top = sorted(fillers.items(), key=lambda x: x[1], reverse=True)[:5]
49
+ top_str = ", ".join(f'« {w} » ({n}×)' for w, n in top)
50
+ lines.append(f"Mots parasites détectés : {top_str}.")
51
+
52
+ if warning:
53
+ lines.append(
54
+ f"Le ratio de mots parasites est élevé ({filler_ratio:.1%} des mots). "
55
+ "Essayez de les remplacer par des silences ou des formulations plus précises."
56
+ )
57
+ else:
58
+ lines.append(f"Le ratio reste acceptable ({filler_ratio:.1%}).")
59
+
60
+ return lines
61
+
62
+
63
+ # ---------------------------------------------------------------------------
64
+ # Feedback structure
65
+ # ---------------------------------------------------------------------------
66
+
67
+ def _feedback_structure(speech: dict) -> list[str]:
68
+ lines = []
69
+ structure = speech.get("structure", {})
70
+ label = structure.get("structure_label", "insuffisante")
71
+ score = structure.get("structure_score", 0)
72
+
73
+ lines.append(f"Structure du discours : **{label}** ({score}/3).")
74
+
75
+ if not structure.get("has_intro"):
76
+ lines.append("- Ajoutez une **introduction** avec un marqueur d'ouverture (ex. : « Pour commencer… »).")
77
+ if not structure.get("has_body"):
78
+ lines.append("- Le **développement** est trop court : développez votre argumentation en plusieurs phrases.")
79
+ if not structure.get("has_conclusion"):
80
+ lines.append("- Concluez explicitement (ex. : « En résumé… », « Pour conclure… »).")
81
+
82
+ if score == 3:
83
+ lines.append("Les trois parties sont bien présentes.")
84
+
85
+ return lines
86
+
87
+
88
+ # ---------------------------------------------------------------------------
89
+ # Feedback clarté
90
+ # ---------------------------------------------------------------------------
91
+
92
+ def _feedback_clarity(speech: dict) -> list[str]:
93
+ lines = []
94
+ clarity = speech.get("clarity", {})
95
+ score = clarity.get("clarity_score", 0)
96
+ avg_wps = clarity.get("avg_words_per_sentence", 0)
97
+ long_ratio = clarity.get("long_sentence_ratio", 0.0)
98
+ ttr = clarity.get("lexical_diversity", 0.0)
99
+
100
+ if score >= 80:
101
+ lines.append(f"Clarté : **excellente** ({score}/100).")
102
+ elif score >= 60:
103
+ lines.append(f"Clarté : **correcte** ({score}/100).")
104
+ elif score >= 40:
105
+ lines.append(f"Clarté : **à améliorer** ({score}/100).")
106
+ else:
107
+ lines.append(f"Clarté : **insuffisante** ({score}/100).")
108
+
109
+ if avg_wps > 25:
110
+ lines.append(
111
+ f"Vos phrases sont longues en moyenne ({avg_wps:.0f} mots/phrase). "
112
+ "Fractionnez-les pour faciliter la compréhension."
113
+ )
114
+ elif avg_wps > 0:
115
+ lines.append(f"Longueur moyenne des phrases : {avg_wps:.0f} mots — bonne lisibilité.")
116
+
117
+ if long_ratio > 0.3:
118
+ lines.append(
119
+ f"{long_ratio:.0%} de vos phrases dépassent 25 mots. "
120
+ "Privilégiez des phrases courtes et directes."
121
+ )
122
+
123
+ if ttr < 0.4:
124
+ lines.append(
125
+ f"La richesse lexicale est faible (TTR : {ttr:.0%}). "
126
+ "Variez votre vocabulaire pour éviter les répétitions."
127
+ )
128
+ elif ttr > 0.7:
129
+ lines.append(f"Vocabulaire varié et riche (TTR : {ttr:.0%}).")
130
+
131
+ return lines
132
+
133
+
134
+ # ---------------------------------------------------------------------------
135
+ # Point d'entrée
136
+ # ---------------------------------------------------------------------------
137
+
138
+ def generate(sentiment: dict, speech: dict) -> dict:
139
+ """
140
+ Génère un rapport de feedback structuré à partir des résultats
141
+ de sentiment.analyze() et speech.analyze().
142
+
143
+ Retourne :
144
+ {
145
+ "sentiment": list[str],
146
+ "fillers": list[str],
147
+ "structure": list[str],
148
+ "clarity": list[str],
149
+ "summary": str, # phrase de synthèse globale
150
+ }
151
+ }
152
+ """
153
+ sentiment_fb = _feedback_sentiment(sentiment)
154
+ filler_fb = _feedback_fillers(speech)
155
+ structure_fb = _feedback_structure(speech)
156
+ clarity_fb = _feedback_clarity(speech)
157
+
158
+ summary = _build_summary(sentiment, speech)
159
+
160
+ return {
161
+ "sentiment": sentiment_fb,
162
+ "fillers": filler_fb,
163
+ "structure": structure_fb,
164
+ "clarity": clarity_fb,
165
+ "summary": summary,
166
+ }
167
+
168
+
169
+ def _build_summary(sentiment: dict, speech: dict) -> str:
170
+ """Phrase de synthèse globale combinant sentiment, structure et clarté."""
171
+ label = sentiment.get("label", "neutre")
172
+ structure_score = speech.get("structure", {}).get("structure_score", 0)
173
+ clarity_score = speech.get("clarity", {}).get("clarity_score", 0)
174
+ filler_warning = speech.get("filler_warning", False)
175
+
176
+ parts = []
177
+
178
+ tone_map = {"positif": "positif", "négatif": "négatif", "neutre": "neutre"}
179
+ parts.append(f"Ton {tone_map.get(label, 'neutre')}")
180
+
181
+ if structure_score == 3:
182
+ parts.append("structure complète")
183
+ elif structure_score == 2:
184
+ parts.append("structure partielle")
185
+ else:
186
+ parts.append("structure à renforcer")
187
+
188
+ if clarity_score >= 80:
189
+ parts.append("bonne clarté")
190
+ elif clarity_score >= 60:
191
+ parts.append("clarté correcte")
192
+ else:
193
+ parts.append("clarté à améliorer")
194
+
195
+ if filler_warning:
196
+ parts.append("trop de mots parasites")
197
+
198
+ return " · ".join(parts) + "."
src/sentiment.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # sentiment.py — Analyse de sentiment TextBlob (FR + EN)
2
+
3
+ from textblob import TextBlob
4
+ from textblob_fr import PatternTagger, PatternAnalyzer
5
+ from langdetect import detect, LangDetectException
6
+
7
+
8
+ def detect_language(text: str) -> str:
9
+ """Retourne 'fr', 'en', ou 'unknown'."""
10
+ try:
11
+ lang = detect(text)
12
+ return lang if lang in ("fr", "en") else "unknown"
13
+ except LangDetectException:
14
+ return "unknown"
15
+
16
+
17
+ def _polarity_label(polarity: float) -> str:
18
+ if polarity > 0.1:
19
+ return "positif"
20
+ if polarity < -0.1:
21
+ return "négatif"
22
+ return "neutre"
23
+
24
+
25
+ def analyze(text: str, lang: str | None = None) -> dict:
26
+ """
27
+ Analyse le sentiment d'un texte en FR ou EN.
28
+
29
+ Retourne :
30
+ {
31
+ "language": str, # 'fr' | 'en' | 'unknown'
32
+ "polarity": float, # [-1.0, 1.0]
33
+ "subjectivity": float, # [0.0, 1.0] (EN uniquement, sinon None)
34
+ "label": str, # 'positif' | 'négatif' | 'neutre'
35
+ }
36
+ """
37
+ if not text or not text.strip():
38
+ return {"language": "unknown", "polarity": 0.0, "subjectivity": None, "label": "neutre"}
39
+
40
+ detected = lang or detect_language(text)
41
+
42
+ if detected == "fr":
43
+ blob = TextBlob(text, pos_tagger=PatternTagger(), analyzer=PatternAnalyzer())
44
+ polarity = blob.sentiment[0]
45
+ subjectivity = None
46
+ else:
47
+ # Fallback EN pour 'unknown' également
48
+ blob = TextBlob(text)
49
+ polarity = blob.sentiment.polarity
50
+ subjectivity = blob.sentiment.subjectivity
51
+
52
+ return {
53
+ "language": detected,
54
+ "polarity": round(polarity, 4),
55
+ "subjectivity": round(subjectivity, 4) if subjectivity is not None else None,
56
+ "label": _polarity_label(polarity),
57
+ }
src/speech.py ADDED
@@ -0,0 +1,152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # speech.py — Analyse du discours : mots parasites, structure, clarté
2
+
3
+ from .utils import (
4
+ word_count,
5
+ sentence_count,
6
+ avg_words_per_sentence,
7
+ lexical_diversity,
8
+ find_filler_words,
9
+ tokenize_sentences,
10
+ tokenize_words,
11
+ )
12
+
13
+ # ---------------------------------------------------------------------------
14
+ # Seuils de clarté
15
+ # ---------------------------------------------------------------------------
16
+
17
+ # Nombre de mots par phrase au-delà duquel la phrase est considérée longue
18
+ LONG_SENTENCE_THRESHOLD = 25
19
+
20
+ # Ratio de mots parasites / total mots au-delà duquel c'est problématique
21
+ FILLER_RATIO_WARNING = 0.05
22
+
23
+
24
+ # ---------------------------------------------------------------------------
25
+ # Structure du discours
26
+ # ---------------------------------------------------------------------------
27
+
28
+ def detect_structure(text: str) -> dict:
29
+ """
30
+ Évalue la présence d'une introduction, d'un développement et d'une conclusion
31
+ en cherchant des marqueurs discursifs typiques.
32
+ """
33
+ INTRO_MARKERS = {
34
+ "fr": ["tout d'abord", "premièrement", "pour commencer", "je vais",
35
+ "dans cet", "dans cette", "aujourd'hui", "nous allons", "je souhaite"],
36
+ "en": ["first", "firstly", "to begin", "in this", "today", "i will",
37
+ "we will", "i would like", "let me"],
38
+ }
39
+ CONCLUSION_MARKERS = {
40
+ "fr": ["en conclusion", "pour conclure", "en résumé", "ainsi",
41
+ "en définitive", "finalement", "pour terminer", "en somme"],
42
+ "en": ["in conclusion", "to conclude", "in summary", "finally",
43
+ "to sum up", "therefore", "in short", "overall"],
44
+ }
45
+
46
+ text_lower = text.lower()
47
+ sentences = tokenize_sentences(text)
48
+ n = len(sentences)
49
+
50
+ # Détecte la langue dominante des marqueurs
51
+ fr_intro = sum(1 for m in INTRO_MARKERS["fr"] if m in text_lower)
52
+ en_intro = sum(1 for m in INTRO_MARKERS["en"] if m in text_lower)
53
+ lang_hint = "fr" if fr_intro >= en_intro else "en"
54
+
55
+ intro_markers = INTRO_MARKERS[lang_hint]
56
+ conclusion_markers = CONCLUSION_MARKERS[lang_hint]
57
+
58
+ has_intro = any(m in text_lower for m in intro_markers)
59
+ has_conclusion = any(m in text_lower for m in conclusion_markers)
60
+ # Le développement est présent si le texte a au moins 3 phrases
61
+ has_body = n >= 3
62
+
63
+ score = sum([has_intro, has_body, has_conclusion]) # 0-3
64
+
65
+ return {
66
+ "has_intro": has_intro,
67
+ "has_body": has_body,
68
+ "has_conclusion": has_conclusion,
69
+ "structure_score": score, # /3
70
+ "structure_label": _structure_label(score),
71
+ }
72
+
73
+
74
+ def _structure_label(score: int) -> str:
75
+ if score == 3:
76
+ return "complète"
77
+ if score == 2:
78
+ return "partielle"
79
+ return "insuffisante"
80
+
81
+
82
+ # ---------------------------------------------------------------------------
83
+ # Clarté
84
+ # ---------------------------------------------------------------------------
85
+
86
+ def analyze_clarity(text: str, lang: str = "fr") -> dict:
87
+ """
88
+ Mesure la clarté du discours :
89
+ - longueur moyenne des phrases
90
+ - proportion de phrases longues
91
+ - richesse lexicale (TTR)
92
+ - score de clarté global [0-100]
93
+ """
94
+ sentences = tokenize_sentences(text)
95
+ if not sentences:
96
+ return {"avg_words_per_sentence": 0, "long_sentence_ratio": 0.0,
97
+ "lexical_diversity": 0.0, "clarity_score": 0}
98
+
99
+ word_counts = [len(tokenize_words(s)) for s in sentences]
100
+ avg_wps = round(sum(word_counts) / len(word_counts), 2)
101
+ long_ratio = round(
102
+ sum(1 for c in word_counts if c > LONG_SENTENCE_THRESHOLD) / len(word_counts), 4
103
+ )
104
+ ttr = lexical_diversity(text)
105
+
106
+ # Score clarté : pénalise les phrases trop longues et la faible diversité
107
+ clarity = 100
108
+ clarity -= min(40, long_ratio * 100) # jusqu'à -40 pour phrases longues
109
+ clarity -= max(0, (0.4 - ttr) * 50) # jusqu'à -20 pour faible TTR
110
+ clarity = max(0, round(clarity))
111
+
112
+ return {
113
+ "avg_words_per_sentence": avg_wps,
114
+ "long_sentence_ratio": long_ratio,
115
+ "lexical_diversity": ttr,
116
+ "clarity_score": clarity,
117
+ }
118
+
119
+
120
+ # ---------------------------------------------------------------------------
121
+ # Point d'entrée principal
122
+ # ---------------------------------------------------------------------------
123
+
124
+ def analyze(text: str, lang: str = "fr") -> dict:
125
+ """
126
+ Analyse complète du discours.
127
+
128
+ Retourne :
129
+ {
130
+ "word_count": int,
131
+ "sentence_count": int,
132
+ "filler_words": dict[str, int],
133
+ "filler_ratio": float,
134
+ "structure": dict,
135
+ "clarity": dict,
136
+ }
137
+ """
138
+ wc = word_count(text)
139
+ sc = sentence_count(text)
140
+ fillers = find_filler_words(text, lang=lang)
141
+ filler_total = sum(fillers.values())
142
+ filler_ratio = round(filler_total / wc, 4) if wc else 0.0
143
+
144
+ return {
145
+ "word_count": wc,
146
+ "sentence_count": sc,
147
+ "filler_words": fillers,
148
+ "filler_ratio": filler_ratio,
149
+ "filler_warning": filler_ratio > FILLER_RATIO_WARNING,
150
+ "structure": detect_structure(text),
151
+ "clarity": analyze_clarity(text, lang=lang),
152
+ }
src/utils.py ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # utils.py — Nettoyage de texte et fonctions helpers
2
+
3
+ import re
4
+ import unicodedata
5
+
6
+ # ---------------------------------------------------------------------------
7
+ # Mots parasites par langue
8
+ # ---------------------------------------------------------------------------
9
+
10
+ FILLER_WORDS: dict[str, list[str]] = {
11
+ "fr": [
12
+ "euh", "bah", "ben", "bref", "donc", "voilà", "du coup", "en fait",
13
+ "genre", "quoi", "hein", "bon", "eh bien", "alors", "enfin",
14
+ "c'est-à-dire", "tu vois", "vous voyez", "machin", "truc", "chose",
15
+ ],
16
+ "en": [
17
+ "uh", "um", "like", "you know", "so", "basically", "literally",
18
+ "actually", "right", "okay", "well", "i mean", "kind of", "sort of",
19
+ "you see", "stuff", "thing", "things",
20
+ ],
21
+ }
22
+
23
+
24
+ # ---------------------------------------------------------------------------
25
+ # Nettoyage
26
+ # ---------------------------------------------------------------------------
27
+
28
+ def normalize_whitespace(text: str) -> str:
29
+ """Remplace toute séquence d'espaces/tabulations/retours par un espace simple."""
30
+ return re.sub(r"[ \t]+", " ", text).strip()
31
+
32
+
33
+ def clean_text(text: str, *, lower: bool = False) -> str:
34
+ """
35
+ Nettoyage léger : normalise les espaces, supprime les caractères de contrôle.
36
+ Conserve la ponctuation (nécessaire pour la segmentation en phrases).
37
+ """
38
+ # Normalisation Unicode (NFD → NFC)
39
+ text = unicodedata.normalize("NFC", text)
40
+ # Supprime les caractères de contrôle sauf \n
41
+ text = re.sub(r"[^\S\n]+", " ", text)
42
+ text = re.sub(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]", "", text)
43
+ text = normalize_whitespace(text)
44
+ return text.lower() if lower else text
45
+
46
+
47
+ def strip_punctuation(text: str) -> str:
48
+ """Supprime toute ponctuation d'un texte."""
49
+ return re.sub(r"[^\w\s]", " ", text, flags=re.UNICODE)
50
+
51
+
52
+ # ---------------------------------------------------------------------------
53
+ # Tokenisation
54
+ # ---------------------------------------------------------------------------
55
+
56
+ def tokenize_words(text: str, *, remove_stopwords: bool = False) -> list[str]:
57
+ """
58
+ Retourne la liste des tokens (mots) en minuscules, sans ponctuation.
59
+ `remove_stopwords` est un hook réservé à une extension future.
60
+ """
61
+ cleaned = strip_punctuation(clean_text(text, lower=True))
62
+ tokens = [t for t in cleaned.split() if t]
63
+ return tokens
64
+
65
+
66
+ def tokenize_sentences(text: str) -> list[str]:
67
+ """Segmente le texte en phrases sur . ! ? et les variantes avec guillemets."""
68
+ sentences = re.split(r"(?<=[.!?])\s+", text.strip())
69
+ return [s.strip() for s in sentences if s.strip()]
70
+
71
+
72
+ # ---------------------------------------------------------------------------
73
+ # Statistiques de base
74
+ # ---------------------------------------------------------------------------
75
+
76
+ def word_count(text: str) -> int:
77
+ return len(tokenize_words(text))
78
+
79
+
80
+ def sentence_count(text: str) -> int:
81
+ return len(tokenize_sentences(text))
82
+
83
+
84
+ def avg_words_per_sentence(text: str) -> float:
85
+ sentences = tokenize_sentences(text)
86
+ if not sentences:
87
+ return 0.0
88
+ counts = [len(tokenize_words(s)) for s in sentences]
89
+ return round(sum(counts) / len(counts), 2)
90
+
91
+
92
+ def lexical_diversity(text: str) -> float:
93
+ """Type-Token Ratio : proportion de mots uniques. Retourne 0.0 si texte vide."""
94
+ tokens = tokenize_words(text)
95
+ if not tokens:
96
+ return 0.0
97
+ return round(len(set(tokens)) / len(tokens), 4)
98
+
99
+
100
+ # ---------------------------------------------------------------------------
101
+ # Détection de mots parasites
102
+ # ---------------------------------------------------------------------------
103
+
104
+ def find_filler_words(text: str, lang: str = "fr") -> dict[str, int]:
105
+ """
106
+ Retourne un dict {mot_parasite: nombre_d_occurrences} pour la langue donnée.
107
+ La recherche est insensible à la casse et porte sur des mots entiers.
108
+ """
109
+ fillers = FILLER_WORDS.get(lang, FILLER_WORDS["fr"])
110
+ text_lower = text.lower()
111
+ result: dict[str, int] = {}
112
+ for filler in fillers:
113
+ pattern = rf"\b{re.escape(filler)}\b"
114
+ count = len(re.findall(pattern, text_lower))
115
+ if count:
116
+ result[filler] = count
117
+ return result