webscout 8.2.6__py3-none-any.whl → 8.2.8__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 (150) hide show
  1. webscout/AIauto.py +1 -1
  2. webscout/AIutel.py +298 -239
  3. webscout/Extra/Act.md +309 -0
  4. webscout/Extra/GitToolkit/gitapi/README.md +110 -0
  5. webscout/Extra/YTToolkit/README.md +375 -0
  6. webscout/Extra/YTToolkit/ytapi/README.md +44 -0
  7. webscout/Extra/YTToolkit/ytapi/extras.py +92 -19
  8. webscout/Extra/autocoder/autocoder.py +309 -114
  9. webscout/Extra/autocoder/autocoder_utiles.py +15 -15
  10. webscout/Extra/gguf.md +430 -0
  11. webscout/Extra/tempmail/README.md +488 -0
  12. webscout/Extra/weather.md +281 -0
  13. webscout/Litlogger/Readme.md +175 -0
  14. webscout/Provider/AISEARCH/DeepFind.py +41 -37
  15. webscout/Provider/AISEARCH/README.md +279 -0
  16. webscout/Provider/AISEARCH/__init__.py +0 -1
  17. webscout/Provider/AISEARCH/genspark_search.py +228 -86
  18. webscout/Provider/AISEARCH/hika_search.py +11 -11
  19. webscout/Provider/AISEARCH/scira_search.py +324 -322
  20. webscout/Provider/AllenAI.py +7 -14
  21. webscout/Provider/Blackboxai.py +518 -74
  22. webscout/Provider/Cloudflare.py +0 -1
  23. webscout/Provider/Deepinfra.py +23 -21
  24. webscout/Provider/Flowith.py +217 -0
  25. webscout/Provider/FreeGemini.py +250 -0
  26. webscout/Provider/GizAI.py +15 -5
  27. webscout/Provider/Glider.py +11 -8
  28. webscout/Provider/HeckAI.py +80 -52
  29. webscout/Provider/Koboldai.py +7 -4
  30. webscout/Provider/LambdaChat.py +2 -2
  31. webscout/Provider/Marcus.py +10 -18
  32. webscout/Provider/OPENAI/BLACKBOXAI.py +735 -0
  33. webscout/Provider/OPENAI/Cloudflare.py +378 -0
  34. webscout/Provider/OPENAI/FreeGemini.py +282 -0
  35. webscout/Provider/OPENAI/NEMOTRON.py +244 -0
  36. webscout/Provider/OPENAI/README.md +1253 -0
  37. webscout/Provider/OPENAI/__init__.py +8 -0
  38. webscout/Provider/OPENAI/ai4chat.py +293 -286
  39. webscout/Provider/OPENAI/api.py +810 -0
  40. webscout/Provider/OPENAI/base.py +217 -14
  41. webscout/Provider/OPENAI/c4ai.py +373 -367
  42. webscout/Provider/OPENAI/chatgpt.py +7 -0
  43. webscout/Provider/OPENAI/chatgptclone.py +7 -0
  44. webscout/Provider/OPENAI/chatsandbox.py +172 -0
  45. webscout/Provider/OPENAI/deepinfra.py +30 -20
  46. webscout/Provider/OPENAI/e2b.py +6 -0
  47. webscout/Provider/OPENAI/exaai.py +7 -0
  48. webscout/Provider/OPENAI/exachat.py +6 -0
  49. webscout/Provider/OPENAI/flowith.py +162 -0
  50. webscout/Provider/OPENAI/freeaichat.py +359 -352
  51. webscout/Provider/OPENAI/glider.py +323 -316
  52. webscout/Provider/OPENAI/groq.py +361 -354
  53. webscout/Provider/OPENAI/heckai.py +30 -64
  54. webscout/Provider/OPENAI/llmchatco.py +8 -0
  55. webscout/Provider/OPENAI/mcpcore.py +7 -0
  56. webscout/Provider/OPENAI/multichat.py +8 -0
  57. webscout/Provider/OPENAI/netwrck.py +356 -350
  58. webscout/Provider/OPENAI/opkfc.py +8 -0
  59. webscout/Provider/OPENAI/scirachat.py +471 -462
  60. webscout/Provider/OPENAI/sonus.py +9 -0
  61. webscout/Provider/OPENAI/standardinput.py +9 -1
  62. webscout/Provider/OPENAI/textpollinations.py +339 -329
  63. webscout/Provider/OPENAI/toolbaz.py +7 -0
  64. webscout/Provider/OPENAI/typefully.py +355 -0
  65. webscout/Provider/OPENAI/typegpt.py +358 -346
  66. webscout/Provider/OPENAI/uncovrAI.py +7 -0
  67. webscout/Provider/OPENAI/utils.py +103 -7
  68. webscout/Provider/OPENAI/venice.py +12 -0
  69. webscout/Provider/OPENAI/wisecat.py +19 -19
  70. webscout/Provider/OPENAI/writecream.py +7 -0
  71. webscout/Provider/OPENAI/x0gpt.py +7 -0
  72. webscout/Provider/OPENAI/yep.py +50 -21
  73. webscout/Provider/OpenGPT.py +1 -1
  74. webscout/Provider/TTI/AiForce/README.md +159 -0
  75. webscout/Provider/TTI/FreeAIPlayground/README.md +99 -0
  76. webscout/Provider/TTI/ImgSys/README.md +174 -0
  77. webscout/Provider/TTI/MagicStudio/README.md +101 -0
  78. webscout/Provider/TTI/Nexra/README.md +155 -0
  79. webscout/Provider/TTI/PollinationsAI/README.md +146 -0
  80. webscout/Provider/TTI/README.md +128 -0
  81. webscout/Provider/TTI/aiarta/README.md +134 -0
  82. webscout/Provider/TTI/artbit/README.md +100 -0
  83. webscout/Provider/TTI/fastflux/README.md +129 -0
  84. webscout/Provider/TTI/huggingface/README.md +114 -0
  85. webscout/Provider/TTI/piclumen/README.md +161 -0
  86. webscout/Provider/TTI/pixelmuse/README.md +79 -0
  87. webscout/Provider/TTI/talkai/README.md +139 -0
  88. webscout/Provider/TTS/README.md +192 -0
  89. webscout/Provider/TTS/__init__.py +2 -1
  90. webscout/Provider/TTS/speechma.py +500 -100
  91. webscout/Provider/TTS/sthir.py +94 -0
  92. webscout/Provider/TeachAnything.py +3 -7
  93. webscout/Provider/TextPollinationsAI.py +4 -2
  94. webscout/Provider/{aimathgpt.py → UNFINISHED/ChatHub.py} +88 -68
  95. webscout/Provider/UNFINISHED/liner_api_request.py +263 -0
  96. webscout/Provider/UNFINISHED/oivscode.py +351 -0
  97. webscout/Provider/UNFINISHED/test_lmarena.py +119 -0
  98. webscout/Provider/Writecream.py +11 -2
  99. webscout/Provider/__init__.py +8 -14
  100. webscout/Provider/ai4chat.py +4 -58
  101. webscout/Provider/asksteve.py +17 -9
  102. webscout/Provider/cerebras.py +3 -1
  103. webscout/Provider/koala.py +170 -268
  104. webscout/Provider/llmchat.py +3 -0
  105. webscout/Provider/lmarena.py +198 -0
  106. webscout/Provider/meta.py +7 -4
  107. webscout/Provider/samurai.py +223 -0
  108. webscout/Provider/scira_chat.py +4 -2
  109. webscout/Provider/typefully.py +23 -151
  110. webscout/__init__.py +4 -2
  111. webscout/cli.py +3 -28
  112. webscout/conversation.py +35 -35
  113. webscout/litagent/Readme.md +276 -0
  114. webscout/scout/README.md +402 -0
  115. webscout/swiftcli/Readme.md +323 -0
  116. webscout/version.py +1 -1
  117. webscout/webscout_search.py +2 -182
  118. webscout/webscout_search_async.py +1 -179
  119. webscout/zeroart/README.md +89 -0
  120. webscout/zeroart/__init__.py +134 -54
  121. webscout/zeroart/base.py +19 -13
  122. webscout/zeroart/effects.py +101 -99
  123. webscout/zeroart/fonts.py +1239 -816
  124. {webscout-8.2.6.dist-info → webscout-8.2.8.dist-info}/METADATA +116 -74
  125. {webscout-8.2.6.dist-info → webscout-8.2.8.dist-info}/RECORD +130 -103
  126. {webscout-8.2.6.dist-info → webscout-8.2.8.dist-info}/WHEEL +1 -1
  127. webscout-8.2.8.dist-info/entry_points.txt +3 -0
  128. webscout-8.2.8.dist-info/top_level.txt +1 -0
  129. webscout/Provider/AISEARCH/ISou.py +0 -256
  130. webscout/Provider/ElectronHub.py +0 -773
  131. webscout/Provider/Free2GPT.py +0 -241
  132. webscout/Provider/GPTWeb.py +0 -249
  133. webscout/Provider/bagoodex.py +0 -145
  134. webscout/Provider/geminiprorealtime.py +0 -160
  135. webscout/scout/core.py +0 -881
  136. webscout-8.2.6.dist-info/entry_points.txt +0 -3
  137. webscout-8.2.6.dist-info/top_level.txt +0 -2
  138. webstoken/__init__.py +0 -30
  139. webstoken/classifier.py +0 -189
  140. webstoken/keywords.py +0 -216
  141. webstoken/language.py +0 -128
  142. webstoken/ner.py +0 -164
  143. webstoken/normalizer.py +0 -35
  144. webstoken/processor.py +0 -77
  145. webstoken/sentiment.py +0 -206
  146. webstoken/stemmer.py +0 -73
  147. webstoken/tagger.py +0 -60
  148. webstoken/tokenizer.py +0 -158
  149. /webscout/Provider/{Youchat.py → UNFINISHED/Youchat.py} +0 -0
  150. {webscout-8.2.6.dist-info → webscout-8.2.8.dist-info}/licenses/LICENSE.md +0 -0
@@ -1,3 +0,0 @@
1
- [console_scripts]
2
- WEBS = webscout.cli:cli
3
- webscout = webscout.cli:cli
@@ -1,2 +0,0 @@
1
- webscout
2
- webstoken
webstoken/__init__.py DELETED
@@ -1,30 +0,0 @@
1
- """
2
- Webstoken - A pure Python NLP toolkit for text processing
3
- """
4
-
5
- from .tokenizer import SentenceTokenizer, WordTokenizer
6
- from .tagger import POSTagger
7
- from .stemmer import Stemmer
8
- from .normalizer import TextNormalizer
9
- from .processor import process_text
10
- from .ner import NamedEntityRecognizer
11
- from .classifier import TextClassifier, TopicClassifier
12
- from .language import LanguageDetector
13
- from .sentiment import SentimentAnalyzer
14
- from .keywords import KeywordExtractor
15
-
16
- __version__ = '0.1.0'
17
- __all__ = [
18
- 'SentenceTokenizer',
19
- 'WordTokenizer',
20
- 'POSTagger',
21
- 'Stemmer',
22
- 'TextNormalizer',
23
- 'process_text',
24
- 'NamedEntityRecognizer',
25
- 'TextClassifier',
26
- 'TopicClassifier',
27
- 'LanguageDetector',
28
- 'SentimentAnalyzer',
29
- 'KeywordExtractor'
30
- ]
webstoken/classifier.py DELETED
@@ -1,189 +0,0 @@
1
- """
2
- Text classification module using rule-based and statistical approaches.
3
- """
4
-
5
- from typing import Dict, List, Set, Tuple
6
- from collections import Counter
7
- import math
8
- import re
9
-
10
- from .normalizer import TextNormalizer
11
- from .tokenizer import WordTokenizer
12
-
13
-
14
- class TextClassifier:
15
- """Simple text classifier using TF-IDF and cosine similarity."""
16
-
17
- def __init__(self):
18
- self.word_tokenizer = WordTokenizer()
19
- self.normalizer = TextNormalizer()
20
- self.documents: Dict[str, List[str]] = {} # category -> list of documents
21
- self.vocabulary: Set[str] = set()
22
- self.idf_scores: Dict[str, float] = {}
23
- self.category_vectors: Dict[str, Dict[str, float]] = {}
24
-
25
- def train(self, documents: Dict[str, List[str]]) -> None:
26
- """
27
- Train the classifier on labeled documents.
28
-
29
- Args:
30
- documents: Dict mapping categories to lists of documents
31
- """
32
- self.documents = documents
33
-
34
- # Build vocabulary and document frequencies
35
- doc_frequencies: Dict[str, int] = Counter()
36
- total_docs = sum(len(docs) for docs in documents.values())
37
-
38
- for category, docs in documents.items():
39
- for doc in docs:
40
- # Normalize and tokenize
41
- doc = self.normalizer.normalize(doc)
42
- tokens = self.word_tokenizer.tokenize(doc)
43
-
44
- # Update vocabulary and document frequencies
45
- unique_tokens = set(tokens)
46
- self.vocabulary.update(unique_tokens)
47
- doc_frequencies.update(unique_tokens)
48
-
49
- # Calculate IDF scores
50
- self.idf_scores = {
51
- word: math.log(total_docs / (freq + 1))
52
- for word, freq in doc_frequencies.items()
53
- }
54
-
55
- # Calculate TF-IDF vectors for each category
56
- for category, docs in documents.items():
57
- category_vector: Dict[str, float] = {word: 0.0 for word in self.vocabulary}
58
-
59
- for doc in docs:
60
- # Get term frequencies
61
- doc = self.normalizer.normalize(doc)
62
- tokens = self.word_tokenizer.tokenize(doc)
63
- term_freqs = Counter(tokens)
64
-
65
- # Update category vector with TF-IDF scores
66
- for word, tf in term_freqs.items():
67
- if word in self.idf_scores:
68
- category_vector[word] += tf * self.idf_scores[word]
69
-
70
- # Average the scores
71
- for word in category_vector:
72
- category_vector[word] /= len(docs)
73
-
74
- self.category_vectors[category] = category_vector
75
-
76
- def _calculate_vector(self, text: str) -> Dict[str, float]:
77
- """Calculate TF-IDF vector for input text."""
78
- # Normalize and tokenize
79
- text = self.normalizer.normalize(text)
80
- tokens = self.word_tokenizer.tokenize(text)
81
- term_freqs = Counter(tokens)
82
-
83
- # Calculate TF-IDF scores
84
- vector = {word: 0.0 for word in self.vocabulary}
85
- for word, tf in term_freqs.items():
86
- if word in self.idf_scores:
87
- vector[word] = tf * self.idf_scores[word]
88
-
89
- return vector
90
-
91
- def _cosine_similarity(self, vec1: Dict[str, float], vec2: Dict[str, float]) -> float:
92
- """Calculate cosine similarity between two vectors."""
93
- dot_product = sum(vec1[word] * vec2[word] for word in vec1)
94
- norm1 = math.sqrt(sum(score * score for score in vec1.values()))
95
- norm2 = math.sqrt(sum(score * score for score in vec2.values()))
96
-
97
- if norm1 == 0 or norm2 == 0:
98
- return 0.0
99
- return dot_product / (norm1 * norm2)
100
-
101
- def classify(self, text: str) -> List[Tuple[str, float]]:
102
- """
103
- Classify text into categories with confidence scores.
104
-
105
- Returns:
106
- List of (category, confidence) tuples, sorted by confidence
107
- """
108
- if not self.category_vectors:
109
- raise ValueError("Classifier must be trained before classification")
110
-
111
- # Calculate vector for input text
112
- text_vector = self._calculate_vector(text)
113
-
114
- # Calculate similarity with each category
115
- similarities = [
116
- (category, self._cosine_similarity(text_vector, category_vec))
117
- for category, category_vec in self.category_vectors.items()
118
- ]
119
-
120
- # Sort by similarity score
121
- return sorted(similarities, key=lambda x: x[1], reverse=True)
122
-
123
-
124
- class TopicClassifier:
125
- """Rule-based topic classifier using keyword matching."""
126
-
127
- def __init__(self):
128
- # Define topic keywords
129
- self.topic_keywords = {
130
- 'TECHNOLOGY': {
131
- 'computer', 'software', 'hardware', 'internet', 'programming',
132
- 'digital', 'data', 'algorithm', 'code', 'web', 'app', 'mobile',
133
- 'cyber', 'robot', 'ai', 'artificial intelligence', 'machine learning'
134
- },
135
- 'SCIENCE': {
136
- 'research', 'experiment', 'laboratory', 'scientific', 'physics',
137
- 'chemistry', 'biology', 'mathematics', 'theory', 'hypothesis',
138
- 'study', 'discovery', 'innovation', 'analysis', 'observation'
139
- },
140
- 'BUSINESS': {
141
- 'company', 'market', 'finance', 'investment', 'stock', 'trade',
142
- 'economy', 'business', 'corporate', 'startup', 'entrepreneur',
143
- 'profit', 'revenue', 'management', 'strategy', 'commercial'
144
- },
145
- 'POLITICS': {
146
- 'government', 'policy', 'election', 'political', 'democracy',
147
- 'parliament', 'congress', 'law', 'legislation', 'party',
148
- 'vote', 'campaign', 'president', 'minister', 'diplomatic'
149
- },
150
- 'SPORTS': {
151
- 'game', 'team', 'player', 'competition', 'tournament',
152
- 'championship', 'score', 'match', 'athlete', 'sport',
153
- 'win', 'lose', 'victory', 'defeat', 'coach', 'training'
154
- },
155
- 'ENTERTAINMENT': {
156
- 'movie', 'film', 'music', 'song', 'concert', 'actor',
157
- 'actress', 'celebrity', 'show', 'performance', 'art',
158
- 'entertainment', 'theater', 'dance', 'festival', 'media'
159
- }
160
- }
161
-
162
- # Compile regex patterns for each topic
163
- self.topic_patterns = {
164
- topic: re.compile(r'\b(' + '|'.join(re.escape(kw) for kw in keywords) + r')\b', re.IGNORECASE)
165
- for topic, keywords in self.topic_keywords.items()
166
- }
167
-
168
- def classify(self, text: str) -> List[Tuple[str, float]]:
169
- """
170
- Classify text into topics with confidence scores.
171
-
172
- Returns:
173
- List of (topic, confidence) tuples, sorted by confidence
174
- """
175
- # Count keyword matches for each topic
176
- topic_matches = {
177
- topic: len(pattern.findall(text))
178
- for topic, pattern in self.topic_patterns.items()
179
- }
180
-
181
- # Calculate confidence scores
182
- total_matches = sum(topic_matches.values()) or 1 # Avoid division by zero
183
- topic_scores = [
184
- (topic, count / total_matches)
185
- for topic, count in topic_matches.items()
186
- ]
187
-
188
- # Sort by score
189
- return sorted(topic_scores, key=lambda x: x[1], reverse=True)
webstoken/keywords.py DELETED
@@ -1,216 +0,0 @@
1
- """
2
- Keyword extraction module using statistical and graph-based approaches.
3
- """
4
-
5
- from typing import Dict, List, Set, Tuple
6
- from collections import Counter, defaultdict
7
- import math
8
- import re
9
-
10
- from .tokenizer import WordTokenizer
11
- from .normalizer import TextNormalizer
12
-
13
-
14
- class KeywordExtractor:
15
- """Keyword extraction using TF-IDF and TextRank-inspired algorithms."""
16
-
17
- def __init__(self):
18
- self.word_tokenizer = WordTokenizer()
19
- self.normalizer = TextNormalizer()
20
-
21
- # Common words to filter out beyond basic stop words
22
- self.filter_words: Set[str] = {
23
- 'would', 'could', 'should', 'said', 'also', 'may', 'might',
24
- 'must', 'need', 'shall', 'want', 'way', 'time', 'just',
25
- 'now', 'like', 'make', 'made', 'well', 'back', 'even',
26
- 'still', 'way', 'take', 'took', 'get', 'got', 'go', 'went'
27
- }
28
-
29
- def _split_into_sentences(self, text: str) -> List[str]:
30
- """Split text into sentences using simple rules."""
31
- text = re.sub(r'\s+', ' ', text)
32
- sentences = re.split(r'[.!?]+', text)
33
- return [s.strip() for s in sentences if s.strip()]
34
-
35
- def _calculate_word_scores(self, text: str) -> Dict[str, float]:
36
- """Calculate word importance scores using frequency and position."""
37
- # Normalize and tokenize text
38
- text = self.normalizer.normalize(text)
39
- sentences = self._split_into_sentences(text)
40
-
41
- word_scores: Dict[str, float] = defaultdict(float)
42
- word_positions: Dict[str, List[int]] = defaultdict(list)
43
-
44
- # Calculate word frequencies and positions
45
- for i, sentence in enumerate(sentences):
46
- words = self.word_tokenizer.tokenize(sentence)
47
- for j, word in enumerate(words):
48
- word = word.lower()
49
- if (word.isalnum() and
50
- len(word) > 2 and
51
- word not in self.filter_words and
52
- word not in self.normalizer.stop_words):
53
- word_scores[word] += 1
54
- word_positions[word].append(i)
55
-
56
- # Adjust scores based on position
57
- num_sentences = len(sentences)
58
- for word, positions in word_positions.items():
59
- # Words appearing in first or last sentences get bonus
60
- if 0 in positions:
61
- word_scores[word] *= 1.2
62
- if num_sentences - 1 in positions:
63
- word_scores[word] *= 1.1
64
-
65
- # Words appearing throughout text get bonus
66
- coverage = len(set(positions)) / num_sentences
67
- word_scores[word] *= (1 + coverage)
68
-
69
- return word_scores
70
-
71
- def _calculate_word_cooccurrence(self, text: str, window_size: int = 3) -> Dict[str, Dict[str, int]]:
72
- """Calculate word co-occurrence matrix."""
73
- # Normalize and tokenize text
74
- text = self.normalizer.normalize(text)
75
- words = self.word_tokenizer.tokenize(text)
76
-
77
- # Filter words
78
- filtered_words = [
79
- word.lower() for word in words
80
- if (word.isalnum() and
81
- len(word) > 2 and
82
- word.lower() not in self.filter_words and
83
- word.lower() not in self.normalizer.stop_words)
84
- ]
85
-
86
- # Build co-occurrence matrix
87
- cooccurrence: Dict[str, Dict[str, int]] = defaultdict(lambda: defaultdict(int))
88
-
89
- for i, word in enumerate(filtered_words):
90
- for j in range(max(0, i - window_size), min(len(filtered_words), i + window_size + 1)):
91
- if i != j:
92
- cooccurrence[word][filtered_words[j]] += 1
93
- cooccurrence[filtered_words[j]][word] += 1
94
-
95
- return cooccurrence
96
-
97
- def _textrank_scores(self, cooccurrence: Dict[str, Dict[str, int]], damping: float = 0.85,
98
- iterations: int = 30) -> Dict[str, float]:
99
- """Calculate TextRank scores from co-occurrence matrix."""
100
- scores = {word: 1.0 for word in cooccurrence}
101
-
102
- for _ in range(iterations):
103
- new_scores = {}
104
- for word in scores:
105
- if not cooccurrence[word]:
106
- continue
107
-
108
- incoming_score = sum(
109
- scores[other] * cooccurrence[word][other] / sum(cooccurrence[other].values())
110
- for other in cooccurrence[word]
111
- )
112
- new_scores[word] = (1 - damping) + damping * incoming_score
113
-
114
- # Check convergence
115
- score_diff = sum(abs(new_scores[w] - scores[w]) for w in scores)
116
- scores = new_scores
117
- if score_diff < 0.0001:
118
- break
119
-
120
- return scores
121
-
122
- def extract_keywords(self, text: str, num_keywords: int = 10,
123
- use_textrank: bool = True) -> List[Tuple[str, float]]:
124
- """
125
- Extract keywords from text using combined frequency and graph-based approach.
126
-
127
- Args:
128
- text: Input text
129
- num_keywords: Number of keywords to return
130
- use_textrank: Whether to use TextRank algorithm
131
-
132
- Returns:
133
- List of (keyword, score) tuples, sorted by score
134
- """
135
- if not text:
136
- return []
137
-
138
- # Get frequency-based scores
139
- freq_scores = self._calculate_word_scores(text)
140
-
141
- if use_textrank:
142
- # Get TextRank scores
143
- cooccurrence = self._calculate_word_cooccurrence(text)
144
- textrank_scores = self._textrank_scores(cooccurrence)
145
-
146
- # Combine scores
147
- combined_scores = {
148
- word: freq_scores[word] * textrank_scores.get(word, 0)
149
- for word in freq_scores
150
- }
151
- else:
152
- combined_scores = freq_scores
153
-
154
- # Sort and return top keywords
155
- sorted_words = sorted(
156
- combined_scores.items(),
157
- key=lambda x: x[1],
158
- reverse=True
159
- )
160
-
161
- return sorted_words[:num_keywords]
162
-
163
- def extract_keyphrases(self, text: str, num_phrases: int = 5,
164
- min_words: int = 2, max_words: int = 4) -> List[Tuple[str, float]]:
165
- """
166
- Extract key phrases from text.
167
-
168
- Args:
169
- text: Input text
170
- num_phrases: Number of phrases to return
171
- min_words: Minimum words in phrase
172
- max_words: Maximum words in phrase
173
-
174
- Returns:
175
- List of (phrase, score) tuples, sorted by score
176
- """
177
- # Normalize and split into sentences
178
- text = self.normalizer.normalize(text)
179
- sentences = self._split_into_sentences(text)
180
-
181
- # Get word importance scores
182
- word_scores = self._calculate_word_scores(text)
183
-
184
- # Extract candidate phrases
185
- phrases: Dict[str, float] = {}
186
-
187
- for sentence in sentences:
188
- words = self.word_tokenizer.tokenize(sentence)
189
-
190
- # Generate phrases of different lengths
191
- for i in range(len(words)):
192
- for length in range(min_words, min(max_words + 1, len(words) - i + 1)):
193
- phrase_words = words[i:i+length]
194
-
195
- # Filter phrases
196
- if all(
197
- word.isalnum() and
198
- len(word) > 2 and
199
- word.lower() not in self.filter_words and
200
- word.lower() not in self.normalizer.stop_words
201
- for word in phrase_words
202
- ):
203
- phrase = ' '.join(phrase_words)
204
- # Score is average of word scores
205
- score = sum(word_scores.get(word.lower(), 0) for word in phrase_words)
206
- score /= len(phrase_words)
207
- phrases[phrase] = score
208
-
209
- # Sort and return top phrases
210
- sorted_phrases = sorted(
211
- phrases.items(),
212
- key=lambda x: x[1],
213
- reverse=True
214
- )
215
-
216
- return sorted_phrases[:num_phrases]
webstoken/language.py DELETED
@@ -1,128 +0,0 @@
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)