aranorm 1.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- aranorm/__init__.py +117 -0
- aranorm/analysis/__init__.py +33 -0
- aranorm/analysis/corpus_analyzer.py +352 -0
- aranorm/analysis/keyword_extractor.py +180 -0
- aranorm/analysis/readability.py +358 -0
- aranorm/analysis/sentiment_analyzer.py +399 -0
- aranorm/analysis/summarizer.py +302 -0
- aranorm/analysis/text_analyzer.py +236 -0
- aranorm/analysis/text_comparator.py +330 -0
- aranorm/cli.py +734 -0
- aranorm/core/__init__.py +23 -0
- aranorm/core/base.py +129 -0
- aranorm/core/config.py +436 -0
- aranorm/core/pipeline.py +625 -0
- aranorm/core/registry.py +122 -0
- aranorm/core/stop_words_config.py +107 -0
- aranorm/core/stop_words_registry.py +301 -0
- aranorm/data/arabizi_mappings.json +124 -0
- aranorm/data/chat_abbreviations.json +40 -0
- aranorm/data/dialect_mappings.json +311 -0
- aranorm/data/stopwords/arabizi.txt +22 -0
- aranorm/data/stopwords/domains/academic.txt +55 -0
- aranorm/data/stopwords/domains/legal.txt +84 -0
- aranorm/data/stopwords/domains/medical.txt +72 -0
- aranorm/data/stopwords/domains/news.txt +78 -0
- aranorm/data/stopwords/domains/religious.txt +78 -0
- aranorm/data/stopwords/egy.txt +118 -0
- aranorm/data/stopwords/filler.txt +103 -0
- aranorm/data/stopwords/glf.txt +80 -0
- aranorm/data/stopwords/internet.txt +152 -0
- aranorm/data/stopwords/irq.txt +43 -0
- aranorm/data/stopwords/lev.txt +51 -0
- aranorm/data/stopwords/msa.txt +715 -0
- aranorm/data/stopwords/nor.txt +46 -0
- aranorm/data/stopwords/numbers.txt +10 -0
- aranorm/data/stopwords/phrases.txt +91 -0
- aranorm/data/stopwords/sdn.txt +97 -0
- aranorm/data/stopwords/social_media.txt +58 -0
- aranorm/data/stopwords/tun.txt +48 -0
- aranorm/data/stopwords/universal.txt +2449 -0
- aranorm/data/stopwords/yem.txt +40 -0
- aranorm/data/stopwords_categorized.json +461 -0
- aranorm/exceptions/__init__.py +27 -0
- aranorm/exceptions/errors.py +61 -0
- aranorm/integrations/__init__.py +15 -0
- aranorm/integrations/huggingface_integration.py +165 -0
- aranorm/integrations/nltk_stopwords.py +185 -0
- aranorm/integrations/pandas_integration.py +171 -0
- aranorm/integrations/sklearn_stopwords.py +41 -0
- aranorm/integrations/spacy_stopwords.py +71 -0
- aranorm/models/__init__.py +7 -0
- aranorm/models/_transformers_model.py +143 -0
- aranorm/models/coda_model.py +66 -0
- aranorm/models/dialect_id_model.py +31 -0
- aranorm/models/msa_model.py +61 -0
- aranorm/processors/__init__.py +104 -0
- aranorm/processors/_base.py +39 -0
- aranorm/processors/alef_processor.py +24 -0
- aranorm/processors/arabizi_processor.py +56 -0
- aranorm/processors/arabizi_stop_processor.py +48 -0
- aranorm/processors/context_aware_processor.py +112 -0
- aranorm/processors/currency_processor.py +129 -0
- aranorm/processors/date_processor.py +140 -0
- aranorm/processors/diacritics_processor.py +14 -0
- aranorm/processors/dialect_stop_processor.py +56 -0
- aranorm/processors/digits_processor.py +18 -0
- aranorm/processors/domain_stop_processor.py +95 -0
- aranorm/processors/emoji_processor.py +23 -0
- aranorm/processors/hamza_processor.py +15 -0
- aranorm/processors/internet_stop_processor.py +48 -0
- aranorm/processors/ligatures_processor.py +21 -0
- aranorm/processors/morphological_stop_processor.py +141 -0
- aranorm/processors/normalization_processor.py +133 -0
- aranorm/processors/number_words_processor.py +208 -0
- aranorm/processors/phone_processor.py +78 -0
- aranorm/processors/phrase_stop_processor.py +150 -0
- aranorm/processors/platform_processors.py +177 -0
- aranorm/processors/punctuation_processor.py +14 -0
- aranorm/processors/repeated_chars_processor.py +22 -0
- aranorm/processors/spacing_processor.py +27 -0
- aranorm/processors/spelling_processor.py +143 -0
- aranorm/processors/stop_words_processor.py +203 -0
- aranorm/processors/taa_marbuta_processor.py +13 -0
- aranorm/processors/tatweel_processor.py +13 -0
- aranorm/processors/text_cleaning_processors.py +92 -0
- aranorm/processors/unicode_processor.py +15 -0
- aranorm/processors/whitespace_processor.py +15 -0
- aranorm/py.typed +0 -0
- aranorm/stages/__init__.py +33 -0
- aranorm/stages/cleaner.py +55 -0
- aranorm/stages/dialect_id.py +212 -0
- aranorm/stages/dialect_norm.py +243 -0
- aranorm/stages/morphological.py +31 -0
- aranorm/stages/normalizer.py +72 -0
- aranorm/stages/stop_words_stage.py +71 -0
- aranorm/utils/__init__.py +99 -0
- aranorm/utils/cache.py +210 -0
- aranorm/utils/chunker.py +213 -0
- aranorm/utils/constants.py +176 -0
- aranorm/utils/exporters.py +256 -0
- aranorm/utils/helpers.py +22 -0
- aranorm/utils/language_detector.py +329 -0
- aranorm/utils/normalizer_utils.py +234 -0
- aranorm/utils/patterns.py +30 -0
- aranorm/utils/progress.py +187 -0
- aranorm/utils/root_extractor.py +155 -0
- aranorm/utils/stemmer.py +271 -0
- aranorm/utils/text_stats.py +240 -0
- aranorm/utils/tokenizer.py +275 -0
- aranorm/utils/validators.py +17 -0
- aranorm-1.2.0.dist-info/METADATA +437 -0
- aranorm-1.2.0.dist-info/RECORD +116 -0
- aranorm-1.2.0.dist-info/WHEEL +5 -0
- aranorm-1.2.0.dist-info/entry_points.txt +2 -0
- aranorm-1.2.0.dist-info/licenses/LICENSE +21 -0
- aranorm-1.2.0.dist-info/top_level.txt +1 -0
aranorm/__init__.py
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
"""AraNorm: a composable Arabic text normalization stack.
|
|
2
|
+
|
|
3
|
+
Quick start::
|
|
4
|
+
|
|
5
|
+
from aranorm import ArabicNormalizationPipeline, PipelineConfig
|
|
6
|
+
|
|
7
|
+
pipeline = ArabicNormalizationPipeline(PipelineConfig(preset="standard"))
|
|
8
|
+
result = pipeline.process("شلونك حبيبي؟")
|
|
9
|
+
print(result.normalized_text, result.dialect)
|
|
10
|
+
|
|
11
|
+
Stop-words quick start::
|
|
12
|
+
|
|
13
|
+
from aranorm import ArabicNormalizationPipeline, PipelineConfig, StopWordsConfig
|
|
14
|
+
|
|
15
|
+
config = PipelineConfig(
|
|
16
|
+
preset="standard",
|
|
17
|
+
stop_words_config=StopWordsConfig(mode="remove", scope="universal"),
|
|
18
|
+
)
|
|
19
|
+
pipeline = ArabicNormalizationPipeline(config)
|
|
20
|
+
result = pipeline.process("أنا سعيد جداً اليوم")
|
|
21
|
+
print(result.stop_words_removed) # → "سعيد جداً"
|
|
22
|
+
print(result.stop_words_found) # → {"أنا", "اليوم"}
|
|
23
|
+
|
|
24
|
+
Text analysis quick start::
|
|
25
|
+
|
|
26
|
+
from aranorm.analysis import TextAnalyzer, KeywordExtractor, SentimentAnalyzer
|
|
27
|
+
from aranorm.utils import compute_stats, word_tokenize, stem, extract_root
|
|
28
|
+
|
|
29
|
+
analyzer = TextAnalyzer()
|
|
30
|
+
result = analyzer.analyze("النص العربي الذي تريد تحليله")
|
|
31
|
+
print(result.content_words)
|
|
32
|
+
|
|
33
|
+
sa = SentimentAnalyzer()
|
|
34
|
+
sentiment = sa.analyze("هذا المنتج رائع جداً")
|
|
35
|
+
print(sentiment.label, sentiment.score)
|
|
36
|
+
|
|
37
|
+
Caching & export::
|
|
38
|
+
|
|
39
|
+
from aranorm.utils import NormalizationCache, BatchExporter
|
|
40
|
+
|
|
41
|
+
cache = NormalizationCache(pipeline, maxsize=10000)
|
|
42
|
+
result = cache.process("شلونك؟") # first call computes, subsequent calls are instant
|
|
43
|
+
|
|
44
|
+
results = pipeline.process_batch(texts)
|
|
45
|
+
exporter = BatchExporter(results)
|
|
46
|
+
exporter.to_csv("output.csv")
|
|
47
|
+
exporter.to_jsonl("output.jsonl")
|
|
48
|
+
|
|
49
|
+
Config serialization::
|
|
50
|
+
|
|
51
|
+
cfg = PipelineConfig(preset="deep")
|
|
52
|
+
json_str = cfg.to_json()
|
|
53
|
+
cfg2 = PipelineConfig.from_json(json_str)
|
|
54
|
+
assert cfg2.preset == cfg.preset
|
|
55
|
+
"""
|
|
56
|
+
|
|
57
|
+
from aranorm.core import (
|
|
58
|
+
ArabicNormalizationPipeline,
|
|
59
|
+
DialectTarget,
|
|
60
|
+
NormalizationResult,
|
|
61
|
+
PipelineBuilder,
|
|
62
|
+
PipelineConfig,
|
|
63
|
+
Preset,
|
|
64
|
+
Processor,
|
|
65
|
+
ProcessorContext,
|
|
66
|
+
ProcessorFactory,
|
|
67
|
+
ProcessorRegistry,
|
|
68
|
+
StopWordsConfig,
|
|
69
|
+
StopWordsRegistry,
|
|
70
|
+
)
|
|
71
|
+
from aranorm.exceptions import (
|
|
72
|
+
AraNormError,
|
|
73
|
+
BatchProcessingError,
|
|
74
|
+
ConfigurationError,
|
|
75
|
+
DataLoadError,
|
|
76
|
+
DialectDetectionError,
|
|
77
|
+
IntegrationUnavailableError,
|
|
78
|
+
InvalidTextError,
|
|
79
|
+
NormalizationError,
|
|
80
|
+
ProcessingTimeoutError,
|
|
81
|
+
ProcessorNotFoundError,
|
|
82
|
+
)
|
|
83
|
+
|
|
84
|
+
__version__ = "1.2.0"
|
|
85
|
+
__author__ = "AraNorm Contributors"
|
|
86
|
+
__license__ = "MIT"
|
|
87
|
+
|
|
88
|
+
__all__ = [
|
|
89
|
+
# Pipeline
|
|
90
|
+
"ArabicNormalizationPipeline",
|
|
91
|
+
"NormalizationResult",
|
|
92
|
+
"PipelineBuilder",
|
|
93
|
+
"PipelineConfig",
|
|
94
|
+
"Preset",
|
|
95
|
+
"DialectTarget",
|
|
96
|
+
# Stop-words
|
|
97
|
+
"StopWordsConfig",
|
|
98
|
+
"StopWordsRegistry",
|
|
99
|
+
# Base abstractions
|
|
100
|
+
"Processor",
|
|
101
|
+
"ProcessorContext",
|
|
102
|
+
"ProcessorFactory",
|
|
103
|
+
"ProcessorRegistry",
|
|
104
|
+
# Exceptions
|
|
105
|
+
"AraNormError",
|
|
106
|
+
"BatchProcessingError",
|
|
107
|
+
"ConfigurationError",
|
|
108
|
+
"DataLoadError",
|
|
109
|
+
"DialectDetectionError",
|
|
110
|
+
"IntegrationUnavailableError",
|
|
111
|
+
"InvalidTextError",
|
|
112
|
+
"NormalizationError",
|
|
113
|
+
"ProcessingTimeoutError",
|
|
114
|
+
"ProcessorNotFoundError",
|
|
115
|
+
# Version
|
|
116
|
+
"__version__",
|
|
117
|
+
]
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
"""AraNorm text analysis utilities built on top of the stop-words system."""
|
|
2
|
+
|
|
3
|
+
from aranorm.analysis.corpus_analyzer import CorpusAnalyzer, CorpusStopWordsBuilder
|
|
4
|
+
from aranorm.analysis.keyword_extractor import KeywordExtractor, KeywordResult
|
|
5
|
+
from aranorm.analysis.readability import ArabicReadabilityAnalyzer, ReadabilityResult
|
|
6
|
+
from aranorm.analysis.sentiment_analyzer import SentimentAnalyzer, SentimentResult
|
|
7
|
+
from aranorm.analysis.summarizer import ArabicTextSummarizer, SummaryResult
|
|
8
|
+
from aranorm.analysis.text_analyzer import TextAnalyzer, TextAnalysisResult
|
|
9
|
+
from aranorm.analysis.text_comparator import TextComparator, SimilarityResult
|
|
10
|
+
|
|
11
|
+
__all__ = [
|
|
12
|
+
# Text analysis
|
|
13
|
+
"TextAnalyzer",
|
|
14
|
+
"TextAnalysisResult",
|
|
15
|
+
# Sentiment
|
|
16
|
+
"SentimentAnalyzer",
|
|
17
|
+
"SentimentResult",
|
|
18
|
+
# Keywords
|
|
19
|
+
"KeywordExtractor",
|
|
20
|
+
"KeywordResult",
|
|
21
|
+
# Comparison
|
|
22
|
+
"TextComparator",
|
|
23
|
+
"SimilarityResult",
|
|
24
|
+
# Corpus-level
|
|
25
|
+
"CorpusAnalyzer",
|
|
26
|
+
"CorpusStopWordsBuilder",
|
|
27
|
+
# Readability
|
|
28
|
+
"ArabicReadabilityAnalyzer",
|
|
29
|
+
"ReadabilityResult",
|
|
30
|
+
# Summarization
|
|
31
|
+
"ArabicTextSummarizer",
|
|
32
|
+
"SummaryResult",
|
|
33
|
+
]
|
|
@@ -0,0 +1,352 @@
|
|
|
1
|
+
"""Corpus-level analysis: stop-word statistics across multiple texts.
|
|
2
|
+
|
|
3
|
+
Provides two public classes:
|
|
4
|
+
|
|
5
|
+
* :class:`CorpusAnalyzer` — aggregate stop-word / content-word statistics
|
|
6
|
+
across a collection of texts.
|
|
7
|
+
* :class:`CorpusStopWordsBuilder` — derive a custom stop-word list from a
|
|
8
|
+
corpus by ranking words by document frequency and inverse content value.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import math
|
|
14
|
+
from collections import Counter
|
|
15
|
+
from dataclasses import dataclass, field
|
|
16
|
+
from typing import Dict, FrozenSet, Iterable, List, Optional, Set, Tuple
|
|
17
|
+
|
|
18
|
+
from aranorm.core.stop_words_config import StopWordsConfig
|
|
19
|
+
from aranorm.core.stop_words_registry import StopWordsRegistry
|
|
20
|
+
from aranorm.processors.stop_words_processor import StopWordsProcessor
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
# ── Helpers ───────────────────────────────────────────────────────────────────
|
|
24
|
+
|
|
25
|
+
def _tokens(text: str) -> List[str]:
|
|
26
|
+
"""Return cleaned token list (strips punctuation, lowercases)."""
|
|
27
|
+
return [t.strip(".,،؟!؛:()[]{}\"'«»\n\r\t") for t in text.split() if t.strip()]
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
# ── Result dataclasses ────────────────────────────────────────────────────────
|
|
31
|
+
|
|
32
|
+
@dataclass
|
|
33
|
+
class DocumentStats:
|
|
34
|
+
"""Per-document statistics produced by :class:`CorpusAnalyzer`."""
|
|
35
|
+
|
|
36
|
+
index: int
|
|
37
|
+
total_tokens: int
|
|
38
|
+
stop_word_count: int
|
|
39
|
+
content_word_count: int
|
|
40
|
+
stop_word_ratio: float
|
|
41
|
+
content_words: List[str]
|
|
42
|
+
stop_words_found: Set[str]
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@dataclass
|
|
46
|
+
class CorpusAnalysisResult:
|
|
47
|
+
"""Aggregated corpus statistics returned by :class:`CorpusAnalyzer`."""
|
|
48
|
+
|
|
49
|
+
# Corpus-wide totals
|
|
50
|
+
document_count: int
|
|
51
|
+
total_tokens: int
|
|
52
|
+
total_stop_words: int
|
|
53
|
+
total_content_words: int
|
|
54
|
+
corpus_stop_word_ratio: float
|
|
55
|
+
|
|
56
|
+
# Frequency tables
|
|
57
|
+
stop_word_frequency: Dict[str, int] # how often each stop word appears
|
|
58
|
+
content_word_frequency: Dict[str, int] # how often each content word appears
|
|
59
|
+
document_frequency: Dict[str, int] # how many docs contain each word
|
|
60
|
+
top_stop_words: List[Tuple[str, int]] # top-N most frequent stop words
|
|
61
|
+
top_content_words: List[Tuple[str, int]]# top-N most frequent content words
|
|
62
|
+
|
|
63
|
+
# Per-document breakdown
|
|
64
|
+
documents: List[DocumentStats]
|
|
65
|
+
|
|
66
|
+
# Diversity metrics
|
|
67
|
+
stop_word_vocabulary_size: int
|
|
68
|
+
content_word_vocabulary_size: int
|
|
69
|
+
average_stop_word_ratio: float
|
|
70
|
+
lexical_diversity: float # unique content words / total content tokens
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
@dataclass
|
|
74
|
+
class CorpusStopWordsResult:
|
|
75
|
+
"""Output from :class:`CorpusStopWordsBuilder`."""
|
|
76
|
+
|
|
77
|
+
extracted_stop_words: FrozenSet[str]
|
|
78
|
+
candidate_scores: List[Tuple[str, float]] # (word, score) sorted descending
|
|
79
|
+
corpus_size: int
|
|
80
|
+
vocabulary_size: int
|
|
81
|
+
threshold_used: float
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
# ── CorpusAnalyzer ────────────────────────────────────────────────────────────
|
|
85
|
+
|
|
86
|
+
class CorpusAnalyzer:
|
|
87
|
+
"""Aggregate stop-word and content-word statistics across a corpus.
|
|
88
|
+
|
|
89
|
+
Parameters
|
|
90
|
+
----------
|
|
91
|
+
config:
|
|
92
|
+
:class:`~aranorm.core.stop_words_config.StopWordsConfig` used to
|
|
93
|
+
decide which words are stop words. Defaults to universal removal.
|
|
94
|
+
registry:
|
|
95
|
+
Optional shared registry.
|
|
96
|
+
top_n:
|
|
97
|
+
Number of top words to include in the result (default 20).
|
|
98
|
+
|
|
99
|
+
Example
|
|
100
|
+
-------
|
|
101
|
+
>>> analyzer = CorpusAnalyzer()
|
|
102
|
+
>>> result = analyzer.analyze(["أنا سعيد اليوم", "هو يعمل بجد"])
|
|
103
|
+
>>> result.corpus_stop_word_ratio
|
|
104
|
+
0.5
|
|
105
|
+
"""
|
|
106
|
+
|
|
107
|
+
def __init__(
|
|
108
|
+
self,
|
|
109
|
+
config: Optional[StopWordsConfig] = None,
|
|
110
|
+
registry: Optional[StopWordsRegistry] = None,
|
|
111
|
+
top_n: int = 20,
|
|
112
|
+
) -> None:
|
|
113
|
+
self.config = config or StopWordsConfig(mode="remove", scope="universal", remove_filler=True)
|
|
114
|
+
self.registry = registry or StopWordsRegistry()
|
|
115
|
+
self.processor = StopWordsProcessor(config=self.config, registry=self.registry)
|
|
116
|
+
self.top_n = top_n
|
|
117
|
+
|
|
118
|
+
# ── Core ─────────────────────────────────────────────────────────────
|
|
119
|
+
|
|
120
|
+
def analyze(self, texts: Iterable[str]) -> CorpusAnalysisResult:
|
|
121
|
+
"""Return a :class:`CorpusAnalysisResult` for the given corpus.
|
|
122
|
+
|
|
123
|
+
Parameters
|
|
124
|
+
----------
|
|
125
|
+
texts:
|
|
126
|
+
Any iterable of strings (list, generator, file lines …).
|
|
127
|
+
"""
|
|
128
|
+
text_list = [t for t in texts if isinstance(t, str) and t.strip()]
|
|
129
|
+
if not text_list:
|
|
130
|
+
return self._empty_result()
|
|
131
|
+
|
|
132
|
+
doc_count = len(text_list)
|
|
133
|
+
total_tokens = 0
|
|
134
|
+
total_stops = 0
|
|
135
|
+
total_content = 0
|
|
136
|
+
|
|
137
|
+
stop_freq: Counter = Counter()
|
|
138
|
+
content_freq: Counter = Counter()
|
|
139
|
+
doc_freq: Counter = Counter()
|
|
140
|
+
|
|
141
|
+
documents: List[DocumentStats] = []
|
|
142
|
+
|
|
143
|
+
for idx, text in enumerate(text_list):
|
|
144
|
+
sw_result = self.processor.process_detailed(text)
|
|
145
|
+
raw_tokens = _tokens(text)
|
|
146
|
+
n = len(raw_tokens)
|
|
147
|
+
stop_set = sw_result.stop_words_found
|
|
148
|
+
content_words = [t for t in _tokens(sw_result.stop_words_removed) if t]
|
|
149
|
+
|
|
150
|
+
total_tokens += n
|
|
151
|
+
total_stops += len(stop_set)
|
|
152
|
+
total_content += len(content_words)
|
|
153
|
+
|
|
154
|
+
for w in stop_set:
|
|
155
|
+
stop_freq[w] += 1
|
|
156
|
+
for w in content_words:
|
|
157
|
+
content_freq[w] += 1
|
|
158
|
+
for w in set(_tokens(text)):
|
|
159
|
+
doc_freq[w] += 1
|
|
160
|
+
|
|
161
|
+
documents.append(
|
|
162
|
+
DocumentStats(
|
|
163
|
+
index=idx,
|
|
164
|
+
total_tokens=n,
|
|
165
|
+
stop_word_count=len(stop_set),
|
|
166
|
+
content_word_count=len(content_words),
|
|
167
|
+
stop_word_ratio=round(len(stop_set) / n, 4) if n else 0.0,
|
|
168
|
+
content_words=content_words,
|
|
169
|
+
stop_words_found=stop_set,
|
|
170
|
+
)
|
|
171
|
+
)
|
|
172
|
+
|
|
173
|
+
corpus_stop_ratio = round(total_stops / total_tokens, 4) if total_tokens else 0.0
|
|
174
|
+
avg_stop_ratio = round(
|
|
175
|
+
sum(d.stop_word_ratio for d in documents) / doc_count, 4
|
|
176
|
+
)
|
|
177
|
+
unique_content = len(content_freq)
|
|
178
|
+
total_content_tokens = sum(content_freq.values())
|
|
179
|
+
diversity = round(unique_content / total_content_tokens, 4) if total_content_tokens else 0.0
|
|
180
|
+
|
|
181
|
+
return CorpusAnalysisResult(
|
|
182
|
+
document_count=doc_count,
|
|
183
|
+
total_tokens=total_tokens,
|
|
184
|
+
total_stop_words=total_stops,
|
|
185
|
+
total_content_words=total_content,
|
|
186
|
+
corpus_stop_word_ratio=corpus_stop_ratio,
|
|
187
|
+
stop_word_frequency=dict(stop_freq.most_common()),
|
|
188
|
+
content_word_frequency=dict(content_freq.most_common()),
|
|
189
|
+
document_frequency=dict(doc_freq.most_common()),
|
|
190
|
+
top_stop_words=stop_freq.most_common(self.top_n),
|
|
191
|
+
top_content_words=content_freq.most_common(self.top_n),
|
|
192
|
+
documents=documents,
|
|
193
|
+
stop_word_vocabulary_size=len(stop_freq),
|
|
194
|
+
content_word_vocabulary_size=unique_content,
|
|
195
|
+
average_stop_word_ratio=avg_stop_ratio,
|
|
196
|
+
lexical_diversity=diversity,
|
|
197
|
+
)
|
|
198
|
+
|
|
199
|
+
def compare(self, corpus_a: Iterable[str], corpus_b: Iterable[str]) -> Dict[str, object]:
|
|
200
|
+
"""Compare stop-word profiles of two corpora.
|
|
201
|
+
|
|
202
|
+
Returns a dict with keys ``corpus_a``, ``corpus_b``, and
|
|
203
|
+
``overlap`` (stop words appearing in both).
|
|
204
|
+
"""
|
|
205
|
+
result_a = self.analyze(corpus_a)
|
|
206
|
+
result_b = self.analyze(corpus_b)
|
|
207
|
+
words_a = set(result_a.stop_word_frequency)
|
|
208
|
+
words_b = set(result_b.stop_word_frequency)
|
|
209
|
+
return {
|
|
210
|
+
"corpus_a": result_a,
|
|
211
|
+
"corpus_b": result_b,
|
|
212
|
+
"shared_stop_words": words_a & words_b,
|
|
213
|
+
"unique_to_a": words_a - words_b,
|
|
214
|
+
"unique_to_b": words_b - words_a,
|
|
215
|
+
"jaccard_similarity": (
|
|
216
|
+
len(words_a & words_b) / len(words_a | words_b)
|
|
217
|
+
if words_a | words_b
|
|
218
|
+
else 0.0
|
|
219
|
+
),
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
# ── Private ───────────────────────────────────────────────────────────
|
|
223
|
+
|
|
224
|
+
def _empty_result(self) -> CorpusAnalysisResult:
|
|
225
|
+
return CorpusAnalysisResult(
|
|
226
|
+
document_count=0,
|
|
227
|
+
total_tokens=0,
|
|
228
|
+
total_stop_words=0,
|
|
229
|
+
total_content_words=0,
|
|
230
|
+
corpus_stop_word_ratio=0.0,
|
|
231
|
+
stop_word_frequency={},
|
|
232
|
+
content_word_frequency={},
|
|
233
|
+
document_frequency={},
|
|
234
|
+
top_stop_words=[],
|
|
235
|
+
top_content_words=[],
|
|
236
|
+
documents=[],
|
|
237
|
+
stop_word_vocabulary_size=0,
|
|
238
|
+
content_word_vocabulary_size=0,
|
|
239
|
+
average_stop_word_ratio=0.0,
|
|
240
|
+
lexical_diversity=0.0,
|
|
241
|
+
)
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
# ── CorpusStopWordsBuilder ────────────────────────────────────────────────────
|
|
245
|
+
|
|
246
|
+
class CorpusStopWordsBuilder:
|
|
247
|
+
"""Derive a domain-specific stop-word list from a corpus.
|
|
248
|
+
|
|
249
|
+
Words are scored by their *document frequency* — how many documents they
|
|
250
|
+
appear in — normalised by a TF weight. High-DF, low-information words
|
|
251
|
+
are candidates for domain stop words.
|
|
252
|
+
|
|
253
|
+
Parameters
|
|
254
|
+
----------
|
|
255
|
+
min_doc_frequency:
|
|
256
|
+
Minimum number of documents a word must appear in (absolute count).
|
|
257
|
+
Words below this threshold are never candidates.
|
|
258
|
+
max_doc_frequency_ratio:
|
|
259
|
+
Maximum fraction of documents a word may appear in before it is
|
|
260
|
+
considered too common to be a content word (0.0–1.0, default 0.85).
|
|
261
|
+
min_word_length:
|
|
262
|
+
Discard single characters and very short strings (default 2).
|
|
263
|
+
exclude_known_stop_words:
|
|
264
|
+
If *True*, filter out words already in the AraNorm universal list.
|
|
265
|
+
|
|
266
|
+
Example
|
|
267
|
+
-------
|
|
268
|
+
>>> builder = CorpusStopWordsBuilder(min_doc_frequency=3)
|
|
269
|
+
>>> result = builder.build(texts)
|
|
270
|
+
>>> frozenset_of_new_stops = result.extracted_stop_words
|
|
271
|
+
"""
|
|
272
|
+
|
|
273
|
+
def __init__(
|
|
274
|
+
self,
|
|
275
|
+
min_doc_frequency: int = 2,
|
|
276
|
+
max_doc_frequency_ratio: float = 0.85,
|
|
277
|
+
min_word_length: int = 2,
|
|
278
|
+
top_n: int = 100,
|
|
279
|
+
exclude_known_stop_words: bool = False,
|
|
280
|
+
registry: Optional[StopWordsRegistry] = None,
|
|
281
|
+
) -> None:
|
|
282
|
+
self.min_doc_frequency = min_doc_frequency
|
|
283
|
+
self.max_doc_frequency_ratio = max_doc_frequency_ratio
|
|
284
|
+
self.min_word_length = min_word_length
|
|
285
|
+
self.top_n = top_n
|
|
286
|
+
self.exclude_known_stop_words = exclude_known_stop_words
|
|
287
|
+
self._registry = registry or StopWordsRegistry()
|
|
288
|
+
|
|
289
|
+
def build(self, texts: Iterable[str]) -> CorpusStopWordsResult:
|
|
290
|
+
"""Derive a stop-word candidate list from *texts*.
|
|
291
|
+
|
|
292
|
+
Parameters
|
|
293
|
+
----------
|
|
294
|
+
texts:
|
|
295
|
+
Iterable of document strings.
|
|
296
|
+
"""
|
|
297
|
+
text_list = [t for t in texts if isinstance(t, str) and t.strip()]
|
|
298
|
+
n_docs = len(text_list)
|
|
299
|
+
if n_docs == 0:
|
|
300
|
+
return CorpusStopWordsResult(
|
|
301
|
+
extracted_stop_words=frozenset(),
|
|
302
|
+
candidate_scores=[],
|
|
303
|
+
corpus_size=0,
|
|
304
|
+
vocabulary_size=0,
|
|
305
|
+
threshold_used=self.max_doc_frequency_ratio,
|
|
306
|
+
)
|
|
307
|
+
|
|
308
|
+
# Count document frequency and total frequency
|
|
309
|
+
df: Counter = Counter()
|
|
310
|
+
tf: Counter = Counter()
|
|
311
|
+
for text in text_list:
|
|
312
|
+
tokens_in_doc = set(_tokens(text))
|
|
313
|
+
for w in tokens_in_doc:
|
|
314
|
+
df[w] += 1
|
|
315
|
+
for w in _tokens(text):
|
|
316
|
+
tf[w] += 1
|
|
317
|
+
|
|
318
|
+
known_stops: Set[str] = set()
|
|
319
|
+
if self.exclude_known_stop_words:
|
|
320
|
+
known_stops = self._registry.get_words("universal")
|
|
321
|
+
|
|
322
|
+
# Score candidates
|
|
323
|
+
candidates: List[Tuple[str, float]] = []
|
|
324
|
+
threshold = self.max_doc_frequency_ratio
|
|
325
|
+
|
|
326
|
+
for word, doc_count in df.items():
|
|
327
|
+
if len(word) < self.min_word_length:
|
|
328
|
+
continue
|
|
329
|
+
if doc_count < self.min_doc_frequency:
|
|
330
|
+
continue
|
|
331
|
+
df_ratio = doc_count / n_docs
|
|
332
|
+
if df_ratio > threshold:
|
|
333
|
+
continue
|
|
334
|
+
if self.exclude_known_stop_words and word in known_stops:
|
|
335
|
+
continue
|
|
336
|
+
# Score: high DF ratio → more stop-word-like
|
|
337
|
+
idf = math.log((n_docs + 1) / (doc_count + 1))
|
|
338
|
+
score = df_ratio / (idf + 1e-9)
|
|
339
|
+
candidates.append((word, round(score, 6)))
|
|
340
|
+
|
|
341
|
+
# Sort by score descending (most stop-word-like first)
|
|
342
|
+
candidates.sort(key=lambda x: x[1], reverse=True)
|
|
343
|
+
top_candidates = candidates[: self.top_n]
|
|
344
|
+
extracted = frozenset(w for w, _ in top_candidates)
|
|
345
|
+
|
|
346
|
+
return CorpusStopWordsResult(
|
|
347
|
+
extracted_stop_words=extracted,
|
|
348
|
+
candidate_scores=top_candidates,
|
|
349
|
+
corpus_size=n_docs,
|
|
350
|
+
vocabulary_size=len(df),
|
|
351
|
+
threshold_used=threshold,
|
|
352
|
+
)
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
"""Keyword extraction for Arabic texts using stop-word filtering + TF scoring."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import math
|
|
6
|
+
import re
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from typing import Dict, FrozenSet, List, Optional, Set, Tuple
|
|
9
|
+
|
|
10
|
+
from aranorm.core.stop_words_config import StopWordsConfig
|
|
11
|
+
from aranorm.core.stop_words_registry import StopWordsRegistry
|
|
12
|
+
from aranorm.processors.stop_words_processor import StopWordsProcessor
|
|
13
|
+
|
|
14
|
+
_ARABIC_WORD = re.compile(r"[\u0621-\u064A\u0671-\u06D3]{2,}")
|
|
15
|
+
_DIACRITICS = re.compile(r"[\u064B-\u0652\u0670\u0640]")
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _normalise(word: str) -> str:
|
|
19
|
+
word = _DIACRITICS.sub("", word)
|
|
20
|
+
return word.strip(".,،؟!؛:()[]{}\"'«»")
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass
|
|
24
|
+
class KeywordResult:
|
|
25
|
+
"""Result of keyword extraction for one text."""
|
|
26
|
+
|
|
27
|
+
original_text: str
|
|
28
|
+
keywords: List[Tuple[str, float]] # [(word, score), …] sorted by score
|
|
29
|
+
top_keywords: List[str] # just the words, ordered
|
|
30
|
+
keyword_count: int
|
|
31
|
+
content_word_count: int
|
|
32
|
+
stop_word_count: int
|
|
33
|
+
coverage_ratio: float # keywords / total words
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class KeywordExtractor:
|
|
37
|
+
"""Extract the most salient Arabic content words from a text.
|
|
38
|
+
|
|
39
|
+
Uses stop-word removal + term-frequency scoring (with optional
|
|
40
|
+
document-frequency penalty when a reference corpus is provided).
|
|
41
|
+
|
|
42
|
+
Parameters
|
|
43
|
+
----------
|
|
44
|
+
config:
|
|
45
|
+
:class:`~aranorm.core.stop_words_config.StopWordsConfig`.
|
|
46
|
+
registry:
|
|
47
|
+
Optional shared registry.
|
|
48
|
+
top_n:
|
|
49
|
+
Maximum keywords to return per text (default 10).
|
|
50
|
+
min_freq:
|
|
51
|
+
Minimum term frequency to be considered a keyword (default 1).
|
|
52
|
+
min_word_length:
|
|
53
|
+
Minimum character length for a keyword candidate (default 3).
|
|
54
|
+
reference_corpus:
|
|
55
|
+
Optional list of texts used to compute IDF weights. When supplied
|
|
56
|
+
the scorer becomes TF-IDF instead of plain TF.
|
|
57
|
+
|
|
58
|
+
Example
|
|
59
|
+
-------
|
|
60
|
+
>>> extractor = KeywordExtractor(top_n=5)
|
|
61
|
+
>>> result = extractor.extract("الاقتصاد العالمي يشهد تحولات جذرية في ظل الأزمات")
|
|
62
|
+
>>> result.top_keywords
|
|
63
|
+
['الاقتصاد', 'تحولات', 'جذرية', 'الأزمات', 'العالمي']
|
|
64
|
+
"""
|
|
65
|
+
|
|
66
|
+
def __init__(
|
|
67
|
+
self,
|
|
68
|
+
config: Optional[StopWordsConfig] = None,
|
|
69
|
+
registry: Optional[StopWordsRegistry] = None,
|
|
70
|
+
top_n: int = 10,
|
|
71
|
+
min_freq: int = 1,
|
|
72
|
+
min_word_length: int = 3,
|
|
73
|
+
reference_corpus: Optional[List[str]] = None,
|
|
74
|
+
) -> None:
|
|
75
|
+
self.config = config or StopWordsConfig(
|
|
76
|
+
mode="remove", scope="universal", remove_filler=True
|
|
77
|
+
)
|
|
78
|
+
self.registry = registry or StopWordsRegistry()
|
|
79
|
+
self.processor = StopWordsProcessor(config=self.config, registry=self.registry)
|
|
80
|
+
self.top_n = top_n
|
|
81
|
+
self.min_freq = min_freq
|
|
82
|
+
self.min_word_length = min_word_length
|
|
83
|
+
self._idf: Optional[Dict[str, float]] = (
|
|
84
|
+
self._build_idf(reference_corpus) if reference_corpus else None
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
# ── Public ────────────────────────────────────────────────────────────
|
|
88
|
+
|
|
89
|
+
def extract(self, text: str) -> KeywordResult:
|
|
90
|
+
"""Extract keywords from a single *text*."""
|
|
91
|
+
if not text or not text.strip():
|
|
92
|
+
return KeywordResult(
|
|
93
|
+
original_text=text, keywords=[], top_keywords=[],
|
|
94
|
+
keyword_count=0, content_word_count=0,
|
|
95
|
+
stop_word_count=0, coverage_ratio=0.0,
|
|
96
|
+
)
|
|
97
|
+
|
|
98
|
+
tokens = text.split()
|
|
99
|
+
total_words = len(tokens)
|
|
100
|
+
sw_result = self.processor.process_detailed(text)
|
|
101
|
+
stop_set = sw_result.stop_words_found
|
|
102
|
+
|
|
103
|
+
# Collect candidate content words
|
|
104
|
+
tf: Dict[str, int] = {}
|
|
105
|
+
for token in tokens:
|
|
106
|
+
w = _normalise(token)
|
|
107
|
+
if (
|
|
108
|
+
w
|
|
109
|
+
and w not in stop_set
|
|
110
|
+
and _ARABIC_WORD.match(w)
|
|
111
|
+
and len(w) >= self.min_word_length
|
|
112
|
+
):
|
|
113
|
+
tf[w] = tf.get(w, 0) + 1
|
|
114
|
+
|
|
115
|
+
# Score
|
|
116
|
+
scored: List[Tuple[str, float]] = []
|
|
117
|
+
for word, freq in tf.items():
|
|
118
|
+
if freq < self.min_freq:
|
|
119
|
+
continue
|
|
120
|
+
tf_score = freq / total_words
|
|
121
|
+
if self._idf is not None:
|
|
122
|
+
idf = self._idf.get(word, math.log(2))
|
|
123
|
+
score = tf_score * idf
|
|
124
|
+
else:
|
|
125
|
+
# Plain TF with length bonus (longer Arabic words tend to carry more meaning)
|
|
126
|
+
length_bonus = min(len(word) / 10, 0.5)
|
|
127
|
+
score = tf_score + length_bonus
|
|
128
|
+
scored.append((word, round(score, 6)))
|
|
129
|
+
|
|
130
|
+
scored.sort(key=lambda x: x[1], reverse=True)
|
|
131
|
+
top = scored[: self.top_n]
|
|
132
|
+
|
|
133
|
+
content_count = len(tf)
|
|
134
|
+
stop_count = len(stop_set)
|
|
135
|
+
coverage = len(top) / total_words if total_words else 0.0
|
|
136
|
+
|
|
137
|
+
return KeywordResult(
|
|
138
|
+
original_text=text,
|
|
139
|
+
keywords=top,
|
|
140
|
+
top_keywords=[w for w, _ in top],
|
|
141
|
+
keyword_count=len(top),
|
|
142
|
+
content_word_count=content_count,
|
|
143
|
+
stop_word_count=stop_count,
|
|
144
|
+
coverage_ratio=round(coverage, 4),
|
|
145
|
+
)
|
|
146
|
+
|
|
147
|
+
def extract_batch(self, texts: List[str]) -> List[KeywordResult]:
|
|
148
|
+
"""Extract keywords from multiple texts."""
|
|
149
|
+
return [self.extract(t) for t in texts]
|
|
150
|
+
|
|
151
|
+
def extract_common_keywords(
|
|
152
|
+
self, texts: List[str], min_text_occurrences: int = 2
|
|
153
|
+
) -> List[Tuple[str, int]]:
|
|
154
|
+
"""Return keywords that appear in at least *min_text_occurrences* texts."""
|
|
155
|
+
from collections import Counter
|
|
156
|
+
|
|
157
|
+
word_text_count: Counter = Counter()
|
|
158
|
+
for result in self.extract_batch(texts):
|
|
159
|
+
for w in result.top_keywords:
|
|
160
|
+
word_text_count[w] += 1
|
|
161
|
+
|
|
162
|
+
return [
|
|
163
|
+
(w, c) for w, c in word_text_count.most_common()
|
|
164
|
+
if c >= min_text_occurrences
|
|
165
|
+
]
|
|
166
|
+
|
|
167
|
+
# ── Private ───────────────────────────────────────────────────────────
|
|
168
|
+
|
|
169
|
+
def _build_idf(self, corpus: List[str]) -> Dict[str, float]:
|
|
170
|
+
"""Compute IDF weights from a reference corpus."""
|
|
171
|
+
n_docs = len(corpus)
|
|
172
|
+
df: Dict[str, int] = {}
|
|
173
|
+
for text in corpus:
|
|
174
|
+
words = {_normalise(t) for t in text.split() if _normalise(t)}
|
|
175
|
+
for w in words:
|
|
176
|
+
df[w] = df.get(w, 0) + 1
|
|
177
|
+
return {
|
|
178
|
+
w: math.log((n_docs + 1) / (count + 1)) + 1
|
|
179
|
+
for w, count in df.items()
|
|
180
|
+
}
|