File: //opt/textanalyse/tools/readability_tool.py
# tools/readability_tool.py
import re
from textstat import textstat
def _count_syllables_german(word: str) -> int:
"""
Sehr grobe Abschätzung der Silbenanzahl im Deutschen:
Zähle Vokalgruppen (a, e, i, o, u, ä, ö, ü, y).
"""
groups = re.findall(r'[aeiouyäöüy]+', word.lower())
return max(1, len(groups))
def calculate_readability_score(text: str) -> dict:
"""
Berechnet:
- english_score: klassischer Flesch Reading Ease (Textstat-Library)
- german_score: deutsche Flesch-Formel (ungefähr)
Rückgabe: {"english_score": float, "german_score": float}
"""
# English
english_score = textstat.flesch_reading_ease(text)
# German
sentences = re.split(r'[.!?]+', text)
sentences = [s for s in sentences if s.strip()]
words = re.findall(r"\w+", text, flags=re.UNICODE)
syllables = sum(_count_syllables_german(w) for w in words)
if not sentences or not words:
german_score = 0.0
else:
avg_sentence_length = len(words) / len(sentences)
avg_syllables_per_word = syllables / len(words)
# Deutsche Flesch-Formel (Annäherung):
german_score = 180 - avg_sentence_length - (58.5 * avg_syllables_per_word)
return {
"english_score": round(english_score, 2),
"german_score": round(german_score, 2)
}