webscout 6.5__py3-none-any.whl → 6.7__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.
Potentially problematic release.
This version of webscout might be problematic. Click here for more details.
- webscout/Extra/autocoder/autocoder_utiles.py +119 -101
- webscout/Extra/weather.py +5 -5
- webscout/Provider/AISEARCH/__init__.py +2 -0
- webscout/Provider/AISEARCH/ooai.py +155 -0
- webscout/Provider/Amigo.py +70 -85
- webscout/Provider/{prefind.py → Jadve.py} +72 -70
- webscout/Provider/Netwrck.py +239 -0
- webscout/Provider/Openai.py +4 -3
- webscout/Provider/PI.py +2 -2
- webscout/Provider/PizzaGPT.py +3 -3
- webscout/Provider/TeachAnything.py +15 -2
- webscout/Provider/Youchat.py +42 -8
- webscout/Provider/__init__.py +134 -147
- webscout/Provider/meta.py +1 -1
- webscout/Provider/multichat.py +230 -0
- webscout/Provider/promptrefine.py +2 -2
- webscout/Provider/talkai.py +10 -13
- webscout/Provider/turboseek.py +5 -4
- webscout/Provider/tutorai.py +8 -112
- webscout/Provider/typegpt.py +4 -5
- webscout/Provider/x0gpt.py +81 -9
- webscout/Provider/yep.py +123 -361
- webscout/__init__.py +10 -1
- webscout/cli.py +31 -39
- webscout/conversation.py +24 -9
- webscout/exceptions.py +188 -20
- webscout/litprinter/__init__.py +19 -123
- webscout/litprinter/colors.py +54 -0
- webscout/optimizers.py +335 -185
- webscout/scout/__init__.py +2 -5
- webscout/scout/core/__init__.py +7 -0
- webscout/scout/core/crawler.py +140 -0
- webscout/scout/core/scout.py +571 -0
- webscout/scout/core/search_result.py +96 -0
- webscout/scout/core/text_analyzer.py +63 -0
- webscout/scout/core/text_utils.py +277 -0
- webscout/scout/core/web_analyzer.py +52 -0
- webscout/scout/element.py +6 -5
- webscout/update_checker.py +117 -58
- webscout/version.py +1 -1
- webscout/webscout_search.py +1 -1
- webscout/zeroart/base.py +15 -16
- webscout/zeroart/effects.py +1 -1
- webscout/zeroart/fonts.py +1 -1
- {webscout-6.5.dist-info → webscout-6.7.dist-info}/METADATA +9 -172
- {webscout-6.5.dist-info → webscout-6.7.dist-info}/RECORD +63 -45
- {webscout-6.5.dist-info → webscout-6.7.dist-info}/entry_points.txt +1 -1
- webscout-6.7.dist-info/top_level.txt +2 -0
- webstoken/__init__.py +30 -0
- webstoken/classifier.py +189 -0
- webstoken/keywords.py +216 -0
- webstoken/language.py +128 -0
- webstoken/ner.py +164 -0
- webstoken/normalizer.py +35 -0
- webstoken/processor.py +77 -0
- webstoken/sentiment.py +206 -0
- webstoken/stemmer.py +73 -0
- webstoken/t.py +75 -0
- webstoken/tagger.py +60 -0
- webstoken/tokenizer.py +158 -0
- webscout/Provider/Perplexity.py +0 -591
- webscout/Provider/RoboCoders.py +0 -206
- webscout/Provider/genspark.py +0 -225
- webscout/Provider/perplexitylabs.py +0 -265
- webscout/Provider/twitterclone.py +0 -251
- webscout/Provider/upstage.py +0 -230
- webscout-6.5.dist-info/top_level.txt +0 -1
- /webscout/Provider/{felo_search.py → AISEARCH/felo_search.py} +0 -0
- {webscout-6.5.dist-info → webscout-6.7.dist-info}/LICENSE.md +0 -0
- {webscout-6.5.dist-info → webscout-6.7.dist-info}/WHEEL +0 -0
webstoken/language.py
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Language detection module using character and word frequency analysis.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from typing import Dict, List, Set, Tuple
|
|
6
|
+
from collections import Counter
|
|
7
|
+
import re
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class LanguageDetector:
|
|
11
|
+
"""Language detection using character n-gram frequencies."""
|
|
12
|
+
|
|
13
|
+
def __init__(self):
|
|
14
|
+
# Language profiles based on common character sequences
|
|
15
|
+
self.language_profiles = {
|
|
16
|
+
'ENGLISH': {
|
|
17
|
+
'chars': 'etaoinshrdlcumwfgypbvkjxqz',
|
|
18
|
+
'ngrams': {'th', 'he', 'in', 'er', 'an', 're', 'on', 'at', 'en', 'nd',
|
|
19
|
+
'ti', 'es', 'or', 'te', 'of', 'ed', 'is', 'it', 'al', 'ar',
|
|
20
|
+
'st', 'to', 'nt', 'ng', 'se', 'ha', 'as', 'ou', 'io', 'le'},
|
|
21
|
+
'words': {'the', 'be', 'to', 'of', 'and', 'a', 'in', 'that', 'have',
|
|
22
|
+
'i', 'it', 'for', 'not', 'on', 'with', 'he', 'as', 'you',
|
|
23
|
+
'do', 'at'}
|
|
24
|
+
},
|
|
25
|
+
'SPANISH': {
|
|
26
|
+
'chars': 'eaosrnidlctumpbgvyqhfzjñxwk',
|
|
27
|
+
'ngrams': {'de', 'en', 'el', 'la', 'os', 'es', 'as', 'ar', 'er', 'ra',
|
|
28
|
+
'al', 'an', 'do', 'or', 'ta', 'ue', 'io', 'on', 'ro', 'ad',
|
|
29
|
+
'te', 'co', 'st', 'ci', 'nt', 'to', 'lo', 'no', 'po', 'ac'},
|
|
30
|
+
'words': {'de', 'la', 'que', 'el', 'en', 'y', 'a', 'los', 'se', 'del',
|
|
31
|
+
'las', 'un', 'por', 'con', 'no', 'una', 'su', 'para', 'es',
|
|
32
|
+
'al'}
|
|
33
|
+
},
|
|
34
|
+
'FRENCH': {
|
|
35
|
+
'chars': 'esaitnrulodcpmévqfbghàjxèêyçwzùâîôûëïüœ',
|
|
36
|
+
'ngrams': {'es', 'le', 'en', 'de', 'nt', 'on', 're', 'er', 'ai', 'te',
|
|
37
|
+
'la', 'an', 'ou', 'it', 'ur', 'et', 'el', 'se', 'qu', 'me',
|
|
38
|
+
'is', 'ar', 'ce', 'ns', 'us', 'ue', 'ss', 'ie', 'em', 'tr'},
|
|
39
|
+
'words': {'le', 'de', 'un', 'être', 'et', 'à', 'il', 'avoir', 'ne',
|
|
40
|
+
'je', 'son', 'que', 'se', 'qui', 'ce', 'dans', 'en', 'du',
|
|
41
|
+
'elle', 'au'}
|
|
42
|
+
},
|
|
43
|
+
'GERMAN': {
|
|
44
|
+
'chars': 'enisratdhulcgmobwfkzvüpäößjyqxéèêëàáâãåāăąćčĉċďđ',
|
|
45
|
+
'ngrams': {'en', 'er', 'ch', 'de', 'ei', 'in', 'te', 'nd', 'ie', 'ge',
|
|
46
|
+
'st', 'ne', 'be', 'es', 'un', 'zu', 'an', 'ng', 'au', 'it',
|
|
47
|
+
'is', 'he', 'ht', 'se', 'ck', 'ic', 're', 'ns', 'sc', 'tz'},
|
|
48
|
+
'words': {'der', 'die', 'und', 'in', 'den', 'von', 'zu', 'das', 'mit',
|
|
49
|
+
'sich', 'des', 'auf', 'für', 'ist', 'im', 'dem', 'nicht',
|
|
50
|
+
'ein', 'eine', 'als'}
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
# Compile word patterns
|
|
55
|
+
self.word_pattern = re.compile(r'\b\w+\b')
|
|
56
|
+
|
|
57
|
+
def _extract_ngrams(self, text: str, n: int = 2) -> List[str]:
|
|
58
|
+
"""Extract character n-grams from text."""
|
|
59
|
+
text = text.lower()
|
|
60
|
+
return [text[i:i+n] for i in range(len(text)-n+1)]
|
|
61
|
+
|
|
62
|
+
def _calculate_char_frequencies(self, text: str) -> Dict[str, float]:
|
|
63
|
+
"""Calculate character frequencies in text."""
|
|
64
|
+
text = text.lower()
|
|
65
|
+
char_count = Counter(c for c in text if c.isalpha())
|
|
66
|
+
total = sum(char_count.values()) or 1
|
|
67
|
+
return {char: count/total for char, count in char_count.items()}
|
|
68
|
+
|
|
69
|
+
def _calculate_ngram_frequencies(self, text: str) -> Dict[str, float]:
|
|
70
|
+
"""Calculate n-gram frequencies in text."""
|
|
71
|
+
ngrams = self._extract_ngrams(text)
|
|
72
|
+
ngram_count = Counter(ngrams)
|
|
73
|
+
total = sum(ngram_count.values()) or 1
|
|
74
|
+
return {ngram: count/total for ngram, count in ngram_count.items()}
|
|
75
|
+
|
|
76
|
+
def _calculate_word_frequencies(self, text: str) -> Dict[str, float]:
|
|
77
|
+
"""Calculate word frequencies in text."""
|
|
78
|
+
words = self.word_pattern.findall(text.lower())
|
|
79
|
+
word_count = Counter(words)
|
|
80
|
+
total = sum(word_count.values()) or 1
|
|
81
|
+
return {word: count/total for word, count in word_count.items()}
|
|
82
|
+
|
|
83
|
+
def _calculate_similarity(self, freq1: Dict[str, float], freq2: Dict[str, float]) -> float:
|
|
84
|
+
"""Calculate similarity between two frequency distributions."""
|
|
85
|
+
common_keys = set(freq1.keys()) & set(freq2.keys())
|
|
86
|
+
if not common_keys:
|
|
87
|
+
return 0.0
|
|
88
|
+
|
|
89
|
+
similarity = sum(min(freq1.get(k, 0), freq2.get(k, 0)) for k in common_keys)
|
|
90
|
+
return similarity
|
|
91
|
+
|
|
92
|
+
def detect(self, text: str) -> List[Tuple[str, float]]:
|
|
93
|
+
"""
|
|
94
|
+
Detect the language of text with confidence scores.
|
|
95
|
+
|
|
96
|
+
Returns:
|
|
97
|
+
List of (language, confidence) tuples, sorted by confidence
|
|
98
|
+
"""
|
|
99
|
+
if not text:
|
|
100
|
+
return []
|
|
101
|
+
|
|
102
|
+
# Calculate frequencies for input text
|
|
103
|
+
char_freqs = self._calculate_char_frequencies(text)
|
|
104
|
+
ngram_freqs = self._calculate_ngram_frequencies(text)
|
|
105
|
+
word_freqs = self._calculate_word_frequencies(text)
|
|
106
|
+
|
|
107
|
+
# Calculate similarity scores for each language
|
|
108
|
+
scores = []
|
|
109
|
+
for lang, profile in self.language_profiles.items():
|
|
110
|
+
# Character similarity
|
|
111
|
+
char_sim = sum(char_freqs.get(c, 0) for c in profile['chars'])
|
|
112
|
+
|
|
113
|
+
# N-gram similarity
|
|
114
|
+
ngram_sim = sum(ngram_freqs.get(ng, 0) for ng in profile['ngrams'])
|
|
115
|
+
|
|
116
|
+
# Word similarity
|
|
117
|
+
word_sim = sum(word_freqs.get(w, 0) for w in profile['words'])
|
|
118
|
+
|
|
119
|
+
# Combined score (weighted average)
|
|
120
|
+
total_score = (0.3 * char_sim + 0.4 * ngram_sim + 0.3 * word_sim)
|
|
121
|
+
scores.append((lang, total_score))
|
|
122
|
+
|
|
123
|
+
# Normalize scores
|
|
124
|
+
total = sum(score for _, score in scores) or 1
|
|
125
|
+
normalized_scores = [(lang, score/total) for lang, score in scores]
|
|
126
|
+
|
|
127
|
+
# Sort by confidence
|
|
128
|
+
return sorted(normalized_scores, key=lambda x: x[1], reverse=True)
|
webstoken/ner.py
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Named Entity Recognition (NER) module for identifying and classifying named entities.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from typing import List, Tuple, Dict, Set
|
|
6
|
+
import re
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class NamedEntityRecognizer:
|
|
10
|
+
"""Rule-based Named Entity Recognition."""
|
|
11
|
+
|
|
12
|
+
def __init__(self):
|
|
13
|
+
# Common entity patterns
|
|
14
|
+
self.PERSON_TITLES = {
|
|
15
|
+
'mr', 'mrs', 'ms', 'miss', 'dr', 'prof', 'sir', 'madam',
|
|
16
|
+
'lord', 'lady', 'president', 'ceo', 'director'
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
self.ORGANIZATION_SUFFIXES = {
|
|
20
|
+
'inc', 'corp', 'ltd', 'llc', 'company', 'corporation',
|
|
21
|
+
'associates', 'partners', 'foundation', 'institute'
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
self.LOCATION_INDICATORS = {
|
|
25
|
+
'street', 'road', 'avenue', 'boulevard', 'lane', 'drive',
|
|
26
|
+
'circle', 'square', 'park', 'bridge', 'river', 'lake',
|
|
27
|
+
'mountain', 'forest', 'city', 'town', 'village', 'country'
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
self.DATE_MONTHS = {
|
|
31
|
+
'january', 'february', 'march', 'april', 'may', 'june',
|
|
32
|
+
'july', 'august', 'september', 'october', 'november', 'december'
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
# Compile regex patterns
|
|
36
|
+
self.patterns = {
|
|
37
|
+
'EMAIL': re.compile(r'\b[\w\.-]+@[\w\.-]+\.\w+\b'),
|
|
38
|
+
'URL': re.compile(r'https?://(?:[\w-]|(?:%[\da-fA-F]{2}))+'),
|
|
39
|
+
'PHONE': re.compile(r'\+?\d{1,3}[-.\s]?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}'),
|
|
40
|
+
'DATE': re.compile(r'\b\d{1,2}[-/]\d{1,2}[-/]\d{2,4}\b|\b(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[a-z]* \d{1,2},? \d{4}\b'),
|
|
41
|
+
'TIME': re.compile(r'\b\d{1,2}:\d{2}(?::\d{2})?(?:\s*[AaPp][Mm])?\b'),
|
|
42
|
+
'MONEY': re.compile(r'\$\d+(?:,\d{3})*(?:\.\d{2})?|\d+(?:,\d{3})*(?:\.\d{2})?\s*(?:dollars|USD|EUR|GBP)'),
|
|
43
|
+
'PERCENTAGE': re.compile(r'\b\d+(?:\.\d+)?%\b')
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
def is_capitalized(self, word: str) -> bool:
|
|
47
|
+
"""Check if a word is capitalized."""
|
|
48
|
+
return word and word[0].isupper()
|
|
49
|
+
|
|
50
|
+
def extract_entities(self, text: str) -> Dict[str, List[Tuple[str, str]]]:
|
|
51
|
+
"""
|
|
52
|
+
Extract named entities from text.
|
|
53
|
+
|
|
54
|
+
Returns:
|
|
55
|
+
Dict mapping entity types to list of (text, label) tuples
|
|
56
|
+
"""
|
|
57
|
+
entities = {
|
|
58
|
+
'PERSON': [],
|
|
59
|
+
'ORGANIZATION': [],
|
|
60
|
+
'LOCATION': [],
|
|
61
|
+
'DATE': [],
|
|
62
|
+
'TIME': [],
|
|
63
|
+
'MONEY': [],
|
|
64
|
+
'EMAIL': [],
|
|
65
|
+
'URL': [],
|
|
66
|
+
'PHONE': [],
|
|
67
|
+
'PERCENTAGE': []
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
# First find regex pattern matches
|
|
71
|
+
for label, pattern in self.patterns.items():
|
|
72
|
+
for match in pattern.finditer(text):
|
|
73
|
+
entities[label].append((match.group(), label))
|
|
74
|
+
|
|
75
|
+
# Process text word by word for other entities
|
|
76
|
+
words = text.split()
|
|
77
|
+
i = 0
|
|
78
|
+
while i < len(words):
|
|
79
|
+
word = words[i]
|
|
80
|
+
next_word = words[i + 1] if i + 1 < len(words) else None
|
|
81
|
+
|
|
82
|
+
# Check for person names
|
|
83
|
+
if word.lower() in self.PERSON_TITLES and next_word and self.is_capitalized(next_word):
|
|
84
|
+
name_parts = []
|
|
85
|
+
j = i + 1
|
|
86
|
+
while j < len(words) and self.is_capitalized(words[j]):
|
|
87
|
+
name_parts.append(words[j])
|
|
88
|
+
j += 1
|
|
89
|
+
if name_parts:
|
|
90
|
+
entities['PERSON'].append((' '.join(name_parts), 'PERSON'))
|
|
91
|
+
i = j
|
|
92
|
+
continue
|
|
93
|
+
|
|
94
|
+
# Check for organizations
|
|
95
|
+
if self.is_capitalized(word):
|
|
96
|
+
org_parts = [word]
|
|
97
|
+
j = i + 1
|
|
98
|
+
while j < len(words) and (
|
|
99
|
+
self.is_capitalized(words[j]) or
|
|
100
|
+
words[j].lower() in self.ORGANIZATION_SUFFIXES
|
|
101
|
+
):
|
|
102
|
+
org_parts.append(words[j])
|
|
103
|
+
j += 1
|
|
104
|
+
if len(org_parts) > 1 or (
|
|
105
|
+
len(org_parts) == 1 and
|
|
106
|
+
any(suff in word.lower() for suff in self.ORGANIZATION_SUFFIXES)
|
|
107
|
+
):
|
|
108
|
+
entities['ORGANIZATION'].append((' '.join(org_parts), 'ORGANIZATION'))
|
|
109
|
+
i = j
|
|
110
|
+
continue
|
|
111
|
+
|
|
112
|
+
# Check for locations
|
|
113
|
+
if word.lower() in self.LOCATION_INDICATORS and i > 0:
|
|
114
|
+
if self.is_capitalized(words[i - 1]):
|
|
115
|
+
entities['LOCATION'].append((words[i - 1] + ' ' + word, 'LOCATION'))
|
|
116
|
+
|
|
117
|
+
i += 1
|
|
118
|
+
|
|
119
|
+
return entities
|
|
120
|
+
|
|
121
|
+
def tag_text(self, text: str) -> List[Tuple[str, str]]:
|
|
122
|
+
"""
|
|
123
|
+
Tag each word in text with its entity type.
|
|
124
|
+
|
|
125
|
+
Returns:
|
|
126
|
+
List of (word, entity_type) tuples
|
|
127
|
+
"""
|
|
128
|
+
entities = self.extract_entities(text)
|
|
129
|
+
tagged = []
|
|
130
|
+
|
|
131
|
+
# Create a map of word positions to entity labels
|
|
132
|
+
position_labels = {}
|
|
133
|
+
text_lower = text.lower()
|
|
134
|
+
|
|
135
|
+
for entity_type, entity_list in entities.items():
|
|
136
|
+
for entity_text, _ in entity_list:
|
|
137
|
+
start = text_lower.find(entity_text.lower())
|
|
138
|
+
if start != -1:
|
|
139
|
+
end = start + len(entity_text)
|
|
140
|
+
for pos in range(start, end):
|
|
141
|
+
position_labels[pos] = entity_type
|
|
142
|
+
|
|
143
|
+
# Tag each character position
|
|
144
|
+
current_pos = 0
|
|
145
|
+
current_word = []
|
|
146
|
+
current_label = 'O' # Outside any entity
|
|
147
|
+
|
|
148
|
+
for char in text:
|
|
149
|
+
if char.isspace():
|
|
150
|
+
if current_word:
|
|
151
|
+
tagged.append((''.join(current_word), current_label))
|
|
152
|
+
current_word = []
|
|
153
|
+
current_label = 'O'
|
|
154
|
+
else:
|
|
155
|
+
current_word.append(char)
|
|
156
|
+
if current_pos in position_labels:
|
|
157
|
+
current_label = position_labels[current_pos]
|
|
158
|
+
current_pos += 1
|
|
159
|
+
|
|
160
|
+
# Add last word if exists
|
|
161
|
+
if current_word:
|
|
162
|
+
tagged.append((''.join(current_word), current_label))
|
|
163
|
+
|
|
164
|
+
return tagged
|
webstoken/normalizer.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Text normalization utilities.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
from typing import List, Set
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class TextNormalizer:
|
|
10
|
+
"""Text normalization utilities."""
|
|
11
|
+
|
|
12
|
+
def __init__(self):
|
|
13
|
+
self.stop_words: Set[str] = {
|
|
14
|
+
'a', 'an', 'and', 'are', 'as', 'at', 'be', 'by', 'for', 'from',
|
|
15
|
+
'has', 'he', 'in', 'is', 'it', 'its', 'of', 'on', 'that', 'the',
|
|
16
|
+
'to', 'was', 'were', 'will', 'with'
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
def remove_stop_words(self, tokens: List[str]) -> List[str]:
|
|
20
|
+
"""Remove common stop words from token list."""
|
|
21
|
+
return [token for token in tokens if token.lower() not in self.stop_words]
|
|
22
|
+
|
|
23
|
+
def normalize(self, text: str) -> str:
|
|
24
|
+
"""Apply various normalization steps to text."""
|
|
25
|
+
# Convert to lowercase
|
|
26
|
+
text = text.lower()
|
|
27
|
+
|
|
28
|
+
# Replace multiple spaces with single space
|
|
29
|
+
text = re.sub(r'\s+', ' ', text)
|
|
30
|
+
|
|
31
|
+
# Remove special characters except apostrophes within words
|
|
32
|
+
text = re.sub(r'[^a-z0-9\s\']', '', text)
|
|
33
|
+
text = re.sub(r'\s\'|\'\s', ' ', text)
|
|
34
|
+
|
|
35
|
+
return text.strip()
|
webstoken/processor.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Main text processing utilities combining all NLP components.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from typing import Dict, Any, List, Tuple
|
|
6
|
+
|
|
7
|
+
from .tokenizer import SentenceTokenizer, WordTokenizer
|
|
8
|
+
from .tagger import POSTagger
|
|
9
|
+
from .stemmer import Stemmer
|
|
10
|
+
from .normalizer import TextNormalizer
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def process_text(text: str, normalize: bool = True, remove_stops: bool = True) -> Dict[str, Any]:
|
|
14
|
+
"""
|
|
15
|
+
Process text using all available NLP tools.
|
|
16
|
+
|
|
17
|
+
Args:
|
|
18
|
+
text (str): Input text to process
|
|
19
|
+
normalize (bool): Whether to normalize text
|
|
20
|
+
remove_stops (bool): Whether to remove stop words
|
|
21
|
+
|
|
22
|
+
Returns:
|
|
23
|
+
Dict containing processed results with the following structure:
|
|
24
|
+
{
|
|
25
|
+
'sentences': [
|
|
26
|
+
{
|
|
27
|
+
'original': str, # Original sentence
|
|
28
|
+
'tokens': List[str], # Word tokens
|
|
29
|
+
'pos_tags': List[Tuple[str, str]], # (word, tag) pairs
|
|
30
|
+
'stems': List[Tuple[str, str]] # (word, stem) pairs
|
|
31
|
+
},
|
|
32
|
+
...
|
|
33
|
+
],
|
|
34
|
+
'num_sentences': int, # Total number of sentences
|
|
35
|
+
'num_tokens': int # Total number of tokens
|
|
36
|
+
}
|
|
37
|
+
"""
|
|
38
|
+
# Initialize tools
|
|
39
|
+
sentence_tokenizer = SentenceTokenizer()
|
|
40
|
+
word_tokenizer = WordTokenizer()
|
|
41
|
+
pos_tagger = POSTagger()
|
|
42
|
+
stemmer = Stemmer()
|
|
43
|
+
normalizer = TextNormalizer()
|
|
44
|
+
|
|
45
|
+
# Process text
|
|
46
|
+
if normalize:
|
|
47
|
+
text = normalizer.normalize(text)
|
|
48
|
+
|
|
49
|
+
# Get sentences
|
|
50
|
+
sentences = sentence_tokenizer.tokenize(text)
|
|
51
|
+
|
|
52
|
+
# Process each sentence
|
|
53
|
+
processed_sentences = []
|
|
54
|
+
for sentence in sentences:
|
|
55
|
+
# Tokenize words
|
|
56
|
+
tokens = word_tokenizer.tokenize(sentence)
|
|
57
|
+
|
|
58
|
+
# Remove stop words if requested
|
|
59
|
+
if remove_stops:
|
|
60
|
+
tokens = normalizer.remove_stop_words(tokens)
|
|
61
|
+
|
|
62
|
+
# Get POS tags and stems
|
|
63
|
+
tagged = pos_tagger.tag(tokens)
|
|
64
|
+
stems = [(token, stemmer.stem(token)) for token, _ in tagged]
|
|
65
|
+
|
|
66
|
+
processed_sentences.append({
|
|
67
|
+
'original': sentence,
|
|
68
|
+
'tokens': tokens,
|
|
69
|
+
'pos_tags': tagged,
|
|
70
|
+
'stems': stems
|
|
71
|
+
})
|
|
72
|
+
|
|
73
|
+
return {
|
|
74
|
+
'sentences': processed_sentences,
|
|
75
|
+
'num_sentences': len(sentences),
|
|
76
|
+
'num_tokens': sum(len(s['tokens']) for s in processed_sentences)
|
|
77
|
+
}
|
webstoken/sentiment.py
ADDED
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Sentiment analysis module for determining text sentiment and emotion.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from typing import Dict, List, Set, Tuple
|
|
6
|
+
import re
|
|
7
|
+
|
|
8
|
+
from .tokenizer import WordTokenizer
|
|
9
|
+
from .normalizer import TextNormalizer
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class SentimentAnalyzer:
|
|
13
|
+
"""Rule-based sentiment analysis using lexicon approach."""
|
|
14
|
+
|
|
15
|
+
def __init__(self):
|
|
16
|
+
self.word_tokenizer = WordTokenizer()
|
|
17
|
+
self.normalizer = TextNormalizer()
|
|
18
|
+
|
|
19
|
+
# Sentiment lexicons
|
|
20
|
+
self.positive_words: Set[str] = {
|
|
21
|
+
'good', 'great', 'awesome', 'excellent', 'happy', 'wonderful',
|
|
22
|
+
'fantastic', 'amazing', 'love', 'beautiful', 'best', 'perfect',
|
|
23
|
+
'brilliant', 'outstanding', 'superb', 'nice', 'pleasant', 'delightful',
|
|
24
|
+
'positive', 'remarkable', 'terrific', 'incredible', 'enjoyable',
|
|
25
|
+
'favorable', 'marvelous', 'splendid', 'superior', 'worthy', 'right'
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
self.negative_words: Set[str] = {
|
|
29
|
+
'bad', 'terrible', 'awful', 'horrible', 'sad', 'poor', 'wrong',
|
|
30
|
+
'worse', 'worst', 'hate', 'dislike', 'disappointing', 'negative',
|
|
31
|
+
'inferior', 'useless', 'worthless', 'mediocre', 'inadequate',
|
|
32
|
+
'unpleasant', 'unfavorable', 'disagreeable', 'offensive', 'annoying',
|
|
33
|
+
'frustrating', 'irritating', 'disgusting', 'dreadful', 'pathetic'
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
# Emotion lexicons
|
|
37
|
+
self.emotion_words = {
|
|
38
|
+
'JOY': {
|
|
39
|
+
'happy', 'joyful', 'delighted', 'excited', 'pleased', 'glad',
|
|
40
|
+
'cheerful', 'content', 'satisfied', 'elated', 'jubilant',
|
|
41
|
+
'thrilled', 'ecstatic', 'merry', 'peaceful', 'upbeat'
|
|
42
|
+
},
|
|
43
|
+
'SADNESS': {
|
|
44
|
+
'sad', 'unhappy', 'depressed', 'gloomy', 'miserable', 'down',
|
|
45
|
+
'heartbroken', 'disappointed', 'upset', 'distressed', 'grief',
|
|
46
|
+
'sorrow', 'melancholy', 'despair', 'hopeless', 'blue'
|
|
47
|
+
},
|
|
48
|
+
'ANGER': {
|
|
49
|
+
'angry', 'mad', 'furious', 'outraged', 'irritated', 'annoyed',
|
|
50
|
+
'frustrated', 'enraged', 'hostile', 'bitter', 'hateful', 'rage',
|
|
51
|
+
'resentful', 'violent', 'aggressive', 'irate'
|
|
52
|
+
},
|
|
53
|
+
'FEAR': {
|
|
54
|
+
'afraid', 'scared', 'frightened', 'terrified', 'anxious', 'worried',
|
|
55
|
+
'nervous', 'fearful', 'panicked', 'alarmed', 'horrified', 'dread',
|
|
56
|
+
'uneasy', 'stressed', 'concerned', 'apprehensive'
|
|
57
|
+
},
|
|
58
|
+
'SURPRISE': {
|
|
59
|
+
'surprised', 'amazed', 'astonished', 'shocked', 'stunned',
|
|
60
|
+
'startled', 'unexpected', 'incredible', 'unbelievable', 'wonder',
|
|
61
|
+
'awe', 'remarkable', 'mysterious', 'sudden', 'strange'
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
# Intensity modifiers
|
|
66
|
+
self.intensifiers = {
|
|
67
|
+
'very': 1.5,
|
|
68
|
+
'really': 1.5,
|
|
69
|
+
'extremely': 2.0,
|
|
70
|
+
'incredibly': 2.0,
|
|
71
|
+
'absolutely': 2.0,
|
|
72
|
+
'totally': 1.5,
|
|
73
|
+
'completely': 1.5,
|
|
74
|
+
'utterly': 2.0,
|
|
75
|
+
'highly': 1.5,
|
|
76
|
+
'especially': 1.5
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
self.diminishers = {
|
|
80
|
+
'somewhat': 0.5,
|
|
81
|
+
'slightly': 0.5,
|
|
82
|
+
'barely': 0.3,
|
|
83
|
+
'hardly': 0.3,
|
|
84
|
+
'sort of': 0.5,
|
|
85
|
+
'kind of': 0.5,
|
|
86
|
+
'a bit': 0.5,
|
|
87
|
+
'a little': 0.5,
|
|
88
|
+
'not very': 0.3,
|
|
89
|
+
'less': 0.5
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
# Negation words
|
|
93
|
+
self.negation_words = {
|
|
94
|
+
'not', 'no', 'never', 'none', 'nobody', 'nothing', 'neither',
|
|
95
|
+
'nowhere', 'hardly', 'scarcely', 'barely', "don't", "doesn't",
|
|
96
|
+
"didn't", "won't", "wouldn't", "shouldn't", "couldn't", "can't"
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
# Compile patterns
|
|
100
|
+
self.word_pattern = re.compile(r'\b\w+\b')
|
|
101
|
+
|
|
102
|
+
def _get_window_around_word(self, words: List[str], index: int, window_size: int = 3) -> List[str]:
|
|
103
|
+
"""Get a window of words around a given index."""
|
|
104
|
+
start = max(0, index - window_size)
|
|
105
|
+
end = min(len(words), index + window_size + 1)
|
|
106
|
+
return words[start:end]
|
|
107
|
+
|
|
108
|
+
def _is_negated(self, words: List[str], index: int) -> bool:
|
|
109
|
+
"""Check if a word is negated by looking at surrounding context."""
|
|
110
|
+
window = self._get_window_around_word(words, index)
|
|
111
|
+
return any(word in self.negation_words for word in window[:index-window[0]])
|
|
112
|
+
|
|
113
|
+
def _get_intensity_multiplier(self, words: List[str], index: int) -> float:
|
|
114
|
+
"""Get intensity multiplier based on modifiers."""
|
|
115
|
+
window = self._get_window_around_word(words, index)
|
|
116
|
+
multiplier = 1.0
|
|
117
|
+
|
|
118
|
+
for word in window[:index-window[0]]:
|
|
119
|
+
if word in self.intensifiers:
|
|
120
|
+
multiplier *= self.intensifiers[word]
|
|
121
|
+
elif word in self.diminishers:
|
|
122
|
+
multiplier *= self.diminishers[word]
|
|
123
|
+
|
|
124
|
+
return multiplier
|
|
125
|
+
|
|
126
|
+
def analyze_sentiment(self, text: str) -> Dict[str, float]:
|
|
127
|
+
"""
|
|
128
|
+
Analyze sentiment of text.
|
|
129
|
+
|
|
130
|
+
Returns:
|
|
131
|
+
Dict with sentiment scores:
|
|
132
|
+
{
|
|
133
|
+
'polarity': float (-1 to 1),
|
|
134
|
+
'subjectivity': float (0 to 1),
|
|
135
|
+
'confidence': float (0 to 1)
|
|
136
|
+
}
|
|
137
|
+
"""
|
|
138
|
+
# Normalize and tokenize text
|
|
139
|
+
text = self.normalizer.normalize(text)
|
|
140
|
+
words = self.word_tokenizer.tokenize(text)
|
|
141
|
+
|
|
142
|
+
positive_score = 0
|
|
143
|
+
negative_score = 0
|
|
144
|
+
word_count = len(words)
|
|
145
|
+
|
|
146
|
+
for i, word in enumerate(words):
|
|
147
|
+
word = word.lower()
|
|
148
|
+
multiplier = self._get_intensity_multiplier(words, i)
|
|
149
|
+
is_negated = self._is_negated(words, i)
|
|
150
|
+
|
|
151
|
+
if word in self.positive_words:
|
|
152
|
+
score = 1.0 * multiplier
|
|
153
|
+
positive_score += -score if is_negated else score
|
|
154
|
+
elif word in self.negative_words:
|
|
155
|
+
score = 1.0 * multiplier
|
|
156
|
+
negative_score += -score if is_negated else score
|
|
157
|
+
|
|
158
|
+
# Calculate metrics
|
|
159
|
+
total_score = positive_score + negative_score
|
|
160
|
+
total_magnitude = abs(positive_score) + abs(negative_score)
|
|
161
|
+
|
|
162
|
+
if word_count == 0:
|
|
163
|
+
return {'polarity': 0.0, 'subjectivity': 0.0, 'confidence': 0.0}
|
|
164
|
+
|
|
165
|
+
polarity = total_score / (word_count or 1) # Normalize to [-1, 1]
|
|
166
|
+
subjectivity = total_magnitude / (word_count or 1) # Normalize to [0, 1]
|
|
167
|
+
confidence = min(1.0, total_magnitude / (word_count / 2)) # Confidence based on magnitude
|
|
168
|
+
|
|
169
|
+
return {
|
|
170
|
+
'polarity': max(-1.0, min(1.0, polarity)),
|
|
171
|
+
'subjectivity': min(1.0, subjectivity),
|
|
172
|
+
'confidence': confidence
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
def analyze_emotions(self, text: str) -> List[Tuple[str, float]]:
|
|
176
|
+
"""
|
|
177
|
+
Analyze emotions in text.
|
|
178
|
+
|
|
179
|
+
Returns:
|
|
180
|
+
List of (emotion, score) tuples, sorted by score
|
|
181
|
+
"""
|
|
182
|
+
# Normalize and tokenize text
|
|
183
|
+
text = self.normalizer.normalize(text)
|
|
184
|
+
words = self.word_tokenizer.tokenize(text)
|
|
185
|
+
|
|
186
|
+
emotion_scores = {emotion: 0.0 for emotion in self.emotion_words}
|
|
187
|
+
|
|
188
|
+
for i, word in enumerate(words):
|
|
189
|
+
word = word.lower()
|
|
190
|
+
multiplier = self._get_intensity_multiplier(words, i)
|
|
191
|
+
is_negated = self._is_negated(words, i)
|
|
192
|
+
|
|
193
|
+
for emotion, emotion_set in self.emotion_words.items():
|
|
194
|
+
if word in emotion_set:
|
|
195
|
+
score = 1.0 * multiplier
|
|
196
|
+
emotion_scores[emotion] += -score if is_negated else score
|
|
197
|
+
|
|
198
|
+
# Normalize scores
|
|
199
|
+
max_score = max(abs(score) for score in emotion_scores.values()) or 1
|
|
200
|
+
normalized_scores = [
|
|
201
|
+
(emotion, score/max_score)
|
|
202
|
+
for emotion, score in emotion_scores.items()
|
|
203
|
+
]
|
|
204
|
+
|
|
205
|
+
# Sort by score
|
|
206
|
+
return sorted(normalized_scores, key=lambda x: x[1], reverse=True)
|