webscout 7.1__py3-none-any.whl → 7.3__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.

Files changed (154) hide show
  1. webscout/AIauto.py +191 -191
  2. webscout/AIbase.py +122 -122
  3. webscout/AIutel.py +440 -440
  4. webscout/Bard.py +343 -161
  5. webscout/DWEBS.py +489 -492
  6. webscout/Extra/YTToolkit/YTdownloader.py +995 -995
  7. webscout/Extra/YTToolkit/__init__.py +2 -2
  8. webscout/Extra/YTToolkit/transcriber.py +476 -479
  9. webscout/Extra/YTToolkit/ytapi/channel.py +307 -307
  10. webscout/Extra/YTToolkit/ytapi/playlist.py +58 -58
  11. webscout/Extra/YTToolkit/ytapi/pool.py +7 -7
  12. webscout/Extra/YTToolkit/ytapi/utils.py +62 -62
  13. webscout/Extra/YTToolkit/ytapi/video.py +103 -103
  14. webscout/Extra/autocoder/__init__.py +9 -9
  15. webscout/Extra/autocoder/autocoder_utiles.py +199 -199
  16. webscout/Extra/autocoder/rawdog.py +5 -7
  17. webscout/Extra/autollama.py +230 -230
  18. webscout/Extra/gguf.py +3 -3
  19. webscout/Extra/weather.py +171 -171
  20. webscout/LLM.py +442 -442
  21. webscout/Litlogger/__init__.py +67 -681
  22. webscout/Litlogger/core/__init__.py +6 -0
  23. webscout/Litlogger/core/level.py +23 -0
  24. webscout/Litlogger/core/logger.py +166 -0
  25. webscout/Litlogger/handlers/__init__.py +12 -0
  26. webscout/Litlogger/handlers/console.py +33 -0
  27. webscout/Litlogger/handlers/file.py +143 -0
  28. webscout/Litlogger/handlers/network.py +173 -0
  29. webscout/Litlogger/styles/__init__.py +7 -0
  30. webscout/Litlogger/styles/colors.py +249 -0
  31. webscout/Litlogger/styles/formats.py +460 -0
  32. webscout/Litlogger/styles/text.py +87 -0
  33. webscout/Litlogger/utils/__init__.py +6 -0
  34. webscout/Litlogger/utils/detectors.py +154 -0
  35. webscout/Litlogger/utils/formatters.py +200 -0
  36. webscout/Provider/AISEARCH/DeepFind.py +250 -250
  37. webscout/Provider/AISEARCH/ISou.py +277 -0
  38. webscout/Provider/AISEARCH/__init__.py +2 -1
  39. webscout/Provider/Blackboxai.py +3 -3
  40. webscout/Provider/ChatGPTGratis.py +226 -0
  41. webscout/Provider/Cloudflare.py +3 -4
  42. webscout/Provider/DeepSeek.py +218 -0
  43. webscout/Provider/Deepinfra.py +40 -24
  44. webscout/Provider/Free2GPT.py +131 -124
  45. webscout/Provider/Gemini.py +100 -115
  46. webscout/Provider/Glider.py +3 -3
  47. webscout/Provider/Groq.py +5 -1
  48. webscout/Provider/Jadve.py +3 -3
  49. webscout/Provider/Marcus.py +191 -192
  50. webscout/Provider/Netwrck.py +3 -3
  51. webscout/Provider/PI.py +2 -2
  52. webscout/Provider/PizzaGPT.py +2 -3
  53. webscout/Provider/QwenLM.py +311 -0
  54. webscout/Provider/TTI/AiForce/__init__.py +22 -22
  55. webscout/Provider/TTI/AiForce/async_aiforce.py +257 -257
  56. webscout/Provider/TTI/AiForce/sync_aiforce.py +242 -242
  57. webscout/Provider/TTI/FreeAIPlayground/__init__.py +9 -0
  58. webscout/Provider/TTI/FreeAIPlayground/async_freeaiplayground.py +206 -0
  59. webscout/Provider/TTI/FreeAIPlayground/sync_freeaiplayground.py +192 -0
  60. webscout/Provider/TTI/Nexra/__init__.py +22 -22
  61. webscout/Provider/TTI/Nexra/async_nexra.py +286 -286
  62. webscout/Provider/TTI/Nexra/sync_nexra.py +258 -258
  63. webscout/Provider/TTI/PollinationsAI/__init__.py +23 -23
  64. webscout/Provider/TTI/PollinationsAI/async_pollinations.py +330 -330
  65. webscout/Provider/TTI/PollinationsAI/sync_pollinations.py +285 -285
  66. webscout/Provider/TTI/__init__.py +2 -1
  67. webscout/Provider/TTI/artbit/__init__.py +22 -22
  68. webscout/Provider/TTI/artbit/async_artbit.py +184 -184
  69. webscout/Provider/TTI/artbit/sync_artbit.py +176 -176
  70. webscout/Provider/TTI/blackbox/__init__.py +4 -4
  71. webscout/Provider/TTI/blackbox/async_blackbox.py +212 -212
  72. webscout/Provider/TTI/blackbox/sync_blackbox.py +199 -199
  73. webscout/Provider/TTI/deepinfra/__init__.py +4 -4
  74. webscout/Provider/TTI/deepinfra/async_deepinfra.py +227 -227
  75. webscout/Provider/TTI/deepinfra/sync_deepinfra.py +199 -199
  76. webscout/Provider/TTI/huggingface/__init__.py +22 -22
  77. webscout/Provider/TTI/huggingface/async_huggingface.py +199 -199
  78. webscout/Provider/TTI/huggingface/sync_huggingface.py +195 -195
  79. webscout/Provider/TTI/imgninza/__init__.py +4 -4
  80. webscout/Provider/TTI/imgninza/async_ninza.py +214 -214
  81. webscout/Provider/TTI/imgninza/sync_ninza.py +209 -209
  82. webscout/Provider/TTI/talkai/__init__.py +4 -4
  83. webscout/Provider/TTI/talkai/async_talkai.py +229 -229
  84. webscout/Provider/TTI/talkai/sync_talkai.py +207 -207
  85. webscout/Provider/TTS/deepgram.py +182 -182
  86. webscout/Provider/TTS/elevenlabs.py +136 -136
  87. webscout/Provider/TTS/gesserit.py +150 -150
  88. webscout/Provider/TTS/murfai.py +138 -138
  89. webscout/Provider/TTS/parler.py +133 -134
  90. webscout/Provider/TTS/streamElements.py +360 -360
  91. webscout/Provider/TTS/utils.py +280 -280
  92. webscout/Provider/TTS/voicepod.py +116 -116
  93. webscout/Provider/TextPollinationsAI.py +28 -8
  94. webscout/Provider/WiseCat.py +193 -0
  95. webscout/Provider/__init__.py +146 -134
  96. webscout/Provider/cerebras.py +242 -227
  97. webscout/Provider/chatglm.py +204 -204
  98. webscout/Provider/dgaf.py +2 -3
  99. webscout/Provider/freeaichat.py +221 -0
  100. webscout/Provider/gaurish.py +2 -3
  101. webscout/Provider/geminiapi.py +208 -208
  102. webscout/Provider/granite.py +223 -0
  103. webscout/Provider/hermes.py +218 -218
  104. webscout/Provider/llama3mitril.py +179 -179
  105. webscout/Provider/llamatutor.py +3 -3
  106. webscout/Provider/llmchat.py +2 -3
  107. webscout/Provider/meta.py +794 -794
  108. webscout/Provider/multichat.py +331 -331
  109. webscout/Provider/typegpt.py +359 -359
  110. webscout/Provider/yep.py +3 -3
  111. webscout/__init__.py +1 -0
  112. webscout/__main__.py +5 -5
  113. webscout/cli.py +319 -319
  114. webscout/conversation.py +241 -242
  115. webscout/exceptions.py +328 -328
  116. webscout/litagent/__init__.py +28 -28
  117. webscout/litagent/agent.py +2 -3
  118. webscout/litprinter/__init__.py +0 -58
  119. webscout/scout/__init__.py +8 -8
  120. webscout/scout/core.py +884 -884
  121. webscout/scout/element.py +459 -459
  122. webscout/scout/parsers/__init__.py +69 -69
  123. webscout/scout/parsers/html5lib_parser.py +172 -172
  124. webscout/scout/parsers/html_parser.py +236 -236
  125. webscout/scout/parsers/lxml_parser.py +178 -178
  126. webscout/scout/utils.py +38 -38
  127. webscout/swiftcli/__init__.py +811 -811
  128. webscout/update_checker.py +2 -12
  129. webscout/version.py +1 -1
  130. webscout/webscout_search.py +87 -6
  131. webscout/webscout_search_async.py +58 -1
  132. webscout/yep_search.py +297 -0
  133. webscout/zeroart/__init__.py +54 -54
  134. webscout/zeroart/base.py +60 -60
  135. webscout/zeroart/effects.py +99 -99
  136. webscout/zeroart/fonts.py +816 -816
  137. {webscout-7.1.dist-info → webscout-7.3.dist-info}/METADATA +62 -22
  138. webscout-7.3.dist-info/RECORD +223 -0
  139. {webscout-7.1.dist-info → webscout-7.3.dist-info}/WHEEL +1 -1
  140. webstoken/__init__.py +30 -30
  141. webstoken/classifier.py +189 -189
  142. webstoken/keywords.py +216 -216
  143. webstoken/language.py +128 -128
  144. webstoken/ner.py +164 -164
  145. webstoken/normalizer.py +35 -35
  146. webstoken/processor.py +77 -77
  147. webstoken/sentiment.py +206 -206
  148. webstoken/stemmer.py +73 -73
  149. webstoken/tagger.py +60 -60
  150. webstoken/tokenizer.py +158 -158
  151. webscout-7.1.dist-info/RECORD +0 -198
  152. {webscout-7.1.dist-info → webscout-7.3.dist-info}/LICENSE.md +0 -0
  153. {webscout-7.1.dist-info → webscout-7.3.dist-info}/entry_points.txt +0 -0
  154. {webscout-7.1.dist-info → webscout-7.3.dist-info}/top_level.txt +0 -0
webstoken/normalizer.py CHANGED
@@ -1,35 +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()
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 CHANGED
@@ -1,77 +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
- }
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 CHANGED
@@ -1,206 +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)
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)