webscout 6.4__py3-none-any.whl → 6.6__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 (116) hide show
  1. webscout/AIutel.py +7 -54
  2. webscout/DWEBS.py +48 -26
  3. webscout/{YTdownloader.py → Extra/YTToolkit/YTdownloader.py} +990 -1103
  4. webscout/Extra/YTToolkit/__init__.py +3 -0
  5. webscout/{transcriber.py → Extra/YTToolkit/transcriber.py} +1 -1
  6. webscout/Extra/YTToolkit/ytapi/__init__.py +6 -0
  7. webscout/Extra/YTToolkit/ytapi/channel.py +307 -0
  8. webscout/Extra/YTToolkit/ytapi/errors.py +13 -0
  9. webscout/Extra/YTToolkit/ytapi/extras.py +45 -0
  10. webscout/Extra/YTToolkit/ytapi/https.py +88 -0
  11. webscout/Extra/YTToolkit/ytapi/patterns.py +61 -0
  12. webscout/Extra/YTToolkit/ytapi/playlist.py +59 -0
  13. webscout/Extra/YTToolkit/ytapi/pool.py +8 -0
  14. webscout/Extra/YTToolkit/ytapi/query.py +37 -0
  15. webscout/Extra/YTToolkit/ytapi/stream.py +60 -0
  16. webscout/Extra/YTToolkit/ytapi/utils.py +62 -0
  17. webscout/Extra/YTToolkit/ytapi/video.py +102 -0
  18. webscout/Extra/__init__.py +2 -1
  19. webscout/Extra/autocoder/autocoder_utiles.py +119 -101
  20. webscout/Extra/autocoder/rawdog.py +679 -680
  21. webscout/Extra/gguf.py +441 -441
  22. webscout/Extra/markdownlite/__init__.py +862 -0
  23. webscout/Extra/weather_ascii.py +2 -2
  24. webscout/Provider/AISEARCH/__init__.py +2 -0
  25. webscout/Provider/AISEARCH/ooai.py +155 -0
  26. webscout/Provider/Amigo.py +70 -85
  27. webscout/Provider/{prefind.py → Jadve.py} +72 -70
  28. webscout/Provider/Netwrck.py +235 -0
  29. webscout/Provider/Openai.py +4 -3
  30. webscout/Provider/PI.py +292 -221
  31. webscout/Provider/PizzaGPT.py +3 -3
  32. webscout/Provider/Reka.py +0 -1
  33. webscout/Provider/TTS/__init__.py +5 -1
  34. webscout/Provider/TTS/deepgram.py +183 -0
  35. webscout/Provider/TTS/elevenlabs.py +137 -0
  36. webscout/Provider/TTS/gesserit.py +151 -0
  37. webscout/Provider/TTS/murfai.py +139 -0
  38. webscout/Provider/TTS/parler.py +134 -107
  39. webscout/Provider/TTS/streamElements.py +360 -275
  40. webscout/Provider/TTS/utils.py +280 -0
  41. webscout/Provider/TTS/voicepod.py +116 -116
  42. webscout/Provider/TeachAnything.py +15 -2
  43. webscout/Provider/Youchat.py +42 -8
  44. webscout/Provider/__init__.py +8 -21
  45. webscout/Provider/meta.py +794 -779
  46. webscout/Provider/multichat.py +230 -0
  47. webscout/Provider/promptrefine.py +2 -2
  48. webscout/Provider/talkai.py +10 -13
  49. webscout/Provider/turboseek.py +5 -4
  50. webscout/Provider/tutorai.py +8 -112
  51. webscout/Provider/typegpt.py +5 -7
  52. webscout/Provider/x0gpt.py +81 -9
  53. webscout/Provider/yep.py +123 -361
  54. webscout/__init__.py +33 -28
  55. webscout/conversation.py +24 -9
  56. webscout/exceptions.py +188 -20
  57. webscout/litprinter/__init__.py +719 -831
  58. webscout/litprinter/colors.py +54 -0
  59. webscout/optimizers.py +420 -270
  60. webscout/prompt_manager.py +279 -279
  61. webscout/scout/__init__.py +8 -0
  62. webscout/scout/core/__init__.py +7 -0
  63. webscout/scout/core/crawler.py +140 -0
  64. webscout/scout/core/scout.py +571 -0
  65. webscout/scout/core/search_result.py +96 -0
  66. webscout/scout/core/text_analyzer.py +63 -0
  67. webscout/scout/core/text_utils.py +277 -0
  68. webscout/scout/core/web_analyzer.py +52 -0
  69. webscout/scout/core.py +884 -0
  70. webscout/scout/element.py +460 -0
  71. webscout/scout/parsers/__init__.py +69 -0
  72. webscout/scout/parsers/html5lib_parser.py +172 -0
  73. webscout/scout/parsers/html_parser.py +236 -0
  74. webscout/scout/parsers/lxml_parser.py +178 -0
  75. webscout/scout/utils.py +38 -0
  76. webscout/update_checker.py +184 -125
  77. webscout/version.py +1 -1
  78. webscout/zeroart/__init__.py +55 -0
  79. webscout/zeroart/base.py +60 -0
  80. webscout/zeroart/effects.py +99 -0
  81. webscout/zeroart/fonts.py +816 -0
  82. webscout/zerodir/__init__.py +225 -0
  83. {webscout-6.4.dist-info → webscout-6.6.dist-info}/METADATA +18 -231
  84. webscout-6.6.dist-info/RECORD +197 -0
  85. webscout-6.6.dist-info/top_level.txt +2 -0
  86. webstoken/__init__.py +30 -0
  87. webstoken/classifier.py +189 -0
  88. webstoken/keywords.py +216 -0
  89. webstoken/language.py +128 -0
  90. webstoken/ner.py +164 -0
  91. webstoken/normalizer.py +35 -0
  92. webstoken/processor.py +77 -0
  93. webstoken/sentiment.py +206 -0
  94. webstoken/stemmer.py +73 -0
  95. webstoken/t.py +75 -0
  96. webstoken/tagger.py +60 -0
  97. webstoken/tokenizer.py +158 -0
  98. webscout/Agents/Onlinesearcher.py +0 -182
  99. webscout/Agents/__init__.py +0 -2
  100. webscout/Agents/functioncall.py +0 -248
  101. webscout/Bing_search.py +0 -251
  102. webscout/Provider/Perplexity.py +0 -599
  103. webscout/Provider/RoboCoders.py +0 -206
  104. webscout/Provider/genspark.py +0 -225
  105. webscout/Provider/perplexitylabs.py +0 -265
  106. webscout/Provider/twitterclone.py +0 -251
  107. webscout/Provider/upstage.py +0 -230
  108. webscout/gpt4free.py +0 -666
  109. webscout/requestsHTMLfix.py +0 -775
  110. webscout/webai.py +0 -2590
  111. webscout-6.4.dist-info/RECORD +0 -154
  112. webscout-6.4.dist-info/top_level.txt +0 -1
  113. /webscout/Provider/{felo_search.py → AISEARCH/felo_search.py} +0 -0
  114. {webscout-6.4.dist-info → webscout-6.6.dist-info}/LICENSE.md +0 -0
  115. {webscout-6.4.dist-info → webscout-6.6.dist-info}/WHEEL +0 -0
  116. {webscout-6.4.dist-info → webscout-6.6.dist-info}/entry_points.txt +0 -0
webstoken/stemmer.py ADDED
@@ -0,0 +1,73 @@
1
+ """
2
+ Word stemming utilities.
3
+ """
4
+
5
+ from typing import Set
6
+
7
+
8
+ class Stemmer:
9
+ """Simple rule-based stemmer implementing Porter-like rules."""
10
+
11
+ def __init__(self):
12
+ self.vowels: Set[str] = {'a', 'e', 'i', 'o', 'u', 'y'}
13
+ self.doubles: Set[str] = {'bb', 'dd', 'ff', 'gg', 'mm', 'nn', 'pp', 'rr', 'tt'}
14
+
15
+ def is_vowel(self, char: str, prev_char: str = None) -> bool:
16
+ """Check if a character is a vowel, considering 'y' special cases."""
17
+ return char in self.vowels or (char == 'y' and prev_char and prev_char not in self.vowels)
18
+
19
+ def count_syllables(self, word: str) -> int:
20
+ """Count syllables in a word based on vowel sequences."""
21
+ count = 0
22
+ prev_char = None
23
+ for i, char in enumerate(word.lower()):
24
+ if self.is_vowel(char, prev_char) and (i == 0 or not self.is_vowel(prev_char, word[i-2] if i > 1 else None)):
25
+ count += 1
26
+ prev_char = char
27
+ return count or 1
28
+
29
+ def stem(self, word: str) -> str:
30
+ """Apply stemming rules to reduce word to its root form."""
31
+ if len(word) <= 3:
32
+ return word
33
+
34
+ word = word.lower()
35
+
36
+ # Step 1: Handle plurals and past participles
37
+ if word.endswith('sses'):
38
+ word = word[:-2]
39
+ elif word.endswith('ies'):
40
+ word = word[:-2]
41
+ elif word.endswith('ss'):
42
+ pass
43
+ elif word.endswith('s') and len(word) > 4:
44
+ word = word[:-1]
45
+
46
+ # Step 2: Handle -ed and -ing
47
+ if word.endswith('ed') and self.count_syllables(word[:-2]) > 1:
48
+ word = word[:-2]
49
+ elif word.endswith('ing') and self.count_syllables(word[:-3]) > 1:
50
+ word = word[:-3]
51
+
52
+ # Step 3: Handle miscellaneous endings
53
+ if len(word) > 5:
54
+ if word.endswith('ement'):
55
+ word = word[:-5]
56
+ elif word.endswith('ment'):
57
+ word = word[:-4]
58
+ elif word.endswith('ent'):
59
+ word = word[:-3]
60
+
61
+ # Step 4: Handle -ity endings
62
+ if word.endswith('ity') and len(word) > 6:
63
+ word = word[:-3]
64
+ if word.endswith('abil'):
65
+ word = word[:-4] + 'able'
66
+ elif word.endswith('ic'):
67
+ word = word[:-2]
68
+
69
+ # Final step: Remove double consonants at the end
70
+ if len(word) > 2 and word[-2:] in self.doubles:
71
+ word = word[:-1]
72
+
73
+ return word
webstoken/t.py ADDED
@@ -0,0 +1,75 @@
1
+ from webstoken import (
2
+ process_text, NamedEntityRecognizer, TextClassifier,
3
+ TopicClassifier, LanguageDetector, SentimentAnalyzer,
4
+ KeywordExtractor
5
+ )
6
+ from rich import print
7
+ # Example text
8
+ text = """
9
+ Dr. John Smith from Microsoft Corporation visited New York City on January 15th, 2024.
10
+ He presented an excellent paper about artificial intelligence and machine learning at
11
+ the International Technology Conference. The research was incredibly well-received,
12
+ and many attendees were excited about its potential applications in healthcare.
13
+ """
14
+
15
+ print("1. Basic Text Processing")
16
+ print("-" * 50)
17
+ result = process_text(text)
18
+ for sentence_data in result['sentences']:
19
+ print("Original:", sentence_data['original'])
20
+ print("Tokens:", sentence_data['tokens'])
21
+ print("POS Tags:", sentence_data['pos_tags'])
22
+ print("Stems:", sentence_data['stems'])
23
+ print()
24
+
25
+ print("\n2. Named Entity Recognition")
26
+ print("-" * 50)
27
+ ner = NamedEntityRecognizer()
28
+ entities = ner.extract_entities(text)
29
+ for entity_type, entity_list in entities.items():
30
+ if entity_list:
31
+ print(f"{entity_type}:", entity_list)
32
+
33
+ print("\n3. Topic Classification")
34
+ print("-" * 50)
35
+ topic_classifier = TopicClassifier()
36
+ topics = topic_classifier.classify(text)
37
+ print("Topics (with confidence):")
38
+ for topic, confidence in topics[:3]: # Top 3 topics
39
+ print(f"{topic}: {confidence:.2f}")
40
+
41
+ print("\n4. Language Detection")
42
+ print("-" * 50)
43
+ lang_detector = LanguageDetector()
44
+ languages = lang_detector.detect(text)
45
+ print("Detected Languages (with confidence):")
46
+ for lang, confidence in languages:
47
+ print(f"{lang}: {confidence:.2f}")
48
+
49
+ print("\n5. Sentiment Analysis")
50
+ print("-" * 50)
51
+ sentiment_analyzer = SentimentAnalyzer()
52
+ sentiment = sentiment_analyzer.analyze_sentiment(text)
53
+ print("Sentiment Scores:")
54
+ print(f"Polarity: {sentiment['polarity']:.2f}")
55
+ print(f"Subjectivity: {sentiment['subjectivity']:.2f}")
56
+ print(f"Confidence: {sentiment['confidence']:.2f}")
57
+
58
+ print("\nEmotions:")
59
+ emotions = sentiment_analyzer.analyze_emotions(text)
60
+ for emotion, score in emotions:
61
+ if score > 0.1: # Only show significant emotions
62
+ print(f"{emotion}: {score:.2f}")
63
+
64
+ print("\n6. Keyword Extraction")
65
+ print("-" * 50)
66
+ keyword_extractor = KeywordExtractor()
67
+ print("Keywords:")
68
+ keywords = keyword_extractor.extract_keywords(text, num_keywords=5)
69
+ for keyword, score in keywords:
70
+ print(f"{keyword}: {score:.2f}")
71
+
72
+ print("\nKey Phrases:")
73
+ keyphrases = keyword_extractor.extract_keyphrases(text, num_phrases=3)
74
+ for phrase, score in keyphrases:
75
+ print(f"{phrase}: {score:.2f}")
webstoken/tagger.py ADDED
@@ -0,0 +1,60 @@
1
+ """
2
+ Part-of-Speech tagging utilities.
3
+ """
4
+
5
+ from typing import List, Set, Tuple
6
+
7
+
8
+ class POSTagger:
9
+ """Simple rule-based Part-of-Speech tagger."""
10
+
11
+ def __init__(self):
12
+ # Basic rules for POS tagging
13
+ self.noun_suffixes: Set[str] = {'ness', 'ment', 'ship', 'dom', 'hood', 'er', 'or', 'ist'}
14
+ self.verb_suffixes: Set[str] = {'ize', 'ate', 'ify', 'ing', 'ed'}
15
+ self.adj_suffixes: Set[str] = {'able', 'ible', 'al', 'ful', 'ous', 'ive', 'less'}
16
+ self.adv_suffixes: Set[str] = {'ly'}
17
+
18
+ # Common words by POS
19
+ self.determiners: Set[str] = {'the', 'a', 'an', 'this', 'that', 'these', 'those'}
20
+ self.prepositions: Set[str] = {'in', 'on', 'at', 'by', 'with', 'from', 'to', 'for'}
21
+ self.pronouns: Set[str] = {'i', 'you', 'he', 'she', 'it', 'we', 'they', 'me', 'him', 'her'}
22
+
23
+ def tag(self, tokens: List[str]) -> List[Tuple[str, str]]:
24
+ """Assign POS tags to tokens based on rules."""
25
+ tagged = []
26
+ prev_tag = None
27
+
28
+ for i, token in enumerate(tokens):
29
+ word = token.lower()
30
+
31
+ # Check special cases first
32
+ if word in self.determiners:
33
+ tag = 'DET'
34
+ elif word in self.prepositions:
35
+ tag = 'PREP'
36
+ elif word in self.pronouns:
37
+ tag = 'PRON'
38
+ # Check suffixes
39
+ elif any(word.endswith(suffix) for suffix in self.noun_suffixes):
40
+ tag = 'NOUN'
41
+ elif any(word.endswith(suffix) for suffix in self.verb_suffixes):
42
+ tag = 'VERB'
43
+ elif any(word.endswith(suffix) for suffix in self.adj_suffixes):
44
+ tag = 'ADJ'
45
+ elif any(word.endswith(suffix) for suffix in self.adv_suffixes):
46
+ tag = 'ADV'
47
+ # Default cases
48
+ elif word[0].isupper() and i > 0:
49
+ tag = 'PROPN' # Proper noun
50
+ elif word.isdigit():
51
+ tag = 'NUM'
52
+ elif not word.isalnum():
53
+ tag = 'PUNCT'
54
+ else:
55
+ tag = 'NOUN' # Default to noun
56
+
57
+ tagged.append((token, tag))
58
+ prev_tag = tag
59
+
60
+ return tagged
webstoken/tokenizer.py ADDED
@@ -0,0 +1,158 @@
1
+ """
2
+ Tokenization utilities for sentence and word-level tokenization.
3
+ """
4
+
5
+ from typing import List, Dict, Set, Pattern
6
+ import re
7
+
8
+
9
+ class SentenceTokenizer:
10
+ """Advanced sentence tokenizer with support for complex cases and proper formatting."""
11
+
12
+ def __init__(self) -> None:
13
+ # Common abbreviations by category
14
+ self.TITLES: Set[str] = {
15
+ 'mr', 'mrs', 'ms', 'dr', 'prof', 'rev', 'sr', 'jr', 'esq',
16
+ 'hon', 'pres', 'gov', 'atty', 'supt', 'det', 'rev', 'col','maj', 'gen', 'capt', 'cmdr',
17
+ 'lt', 'sgt', 'cpl', 'pvt'
18
+ }
19
+
20
+ self.ACADEMIC: Set[str] = {
21
+ 'ph.d', 'phd', 'm.d', 'md', 'b.a', 'ba', 'm.a', 'ma', 'd.d.s', 'dds',
22
+ 'm.b.a', 'mba', 'b.sc', 'bsc', 'm.sc', 'msc', 'llb', 'll.b', 'bl'
23
+ }
24
+
25
+ self.ORGANIZATIONS: Set[str] = {
26
+ 'inc', 'ltd', 'co', 'corp', 'llc', 'llp', 'assn', 'bros', 'plc', 'cos',
27
+ 'intl', 'dept', 'est', 'dist', 'mfg', 'div'
28
+ }
29
+
30
+ self.MONTHS: Set[str] = {
31
+ 'jan', 'feb', 'mar', 'apr', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'
32
+ }
33
+
34
+ self.UNITS: Set[str] = {
35
+ 'oz', 'pt', 'qt', 'gal', 'ml', 'cc', 'km', 'cm', 'mm', 'ft', 'in',
36
+ 'kg', 'lb', 'lbs', 'hz', 'khz', 'mhz', 'ghz', 'kb', 'mb', 'gb', 'tb'
37
+ }
38
+
39
+ self.TECHNOLOGY: Set[str] = {
40
+ 'v', 'ver', 'app', 'sys', 'dir', 'exe', 'lib', 'api', 'sdk', 'url',
41
+ 'cpu', 'gpu', 'ram', 'rom', 'hdd', 'ssd', 'lan', 'wan', 'sql', 'html'
42
+ }
43
+
44
+ self.MISC: Set[str] = {
45
+ 'vs', 'etc', 'ie', 'eg', 'no', 'al', 'ca', 'cf', 'pp', 'est', 'st',
46
+ 'approx', 'appt', 'apt', 'dept', 'depts', 'min', 'max', 'avg'
47
+ }
48
+
49
+ # Combine all abbreviations
50
+ self.all_abbreviations: Set[str] = (
51
+ self.TITLES | self.ACADEMIC | self.ORGANIZATIONS |
52
+ self.MONTHS | self.UNITS | self.TECHNOLOGY | self.MISC
53
+ )
54
+
55
+ # Special patterns
56
+ self.ELLIPSIS: str = r'\.{2,}|…'
57
+ self.URL_PATTERN: str = (
58
+ r'(?:https?:\/\/|www\.)[\w\-\.]+\.[a-zA-Z]{2,}(?:\/[^\s]*)?'
59
+ )
60
+ self.EMAIL_PATTERN: str = r'[\w\.-]+@[\w\.-]+\.\w+'
61
+ self.NUMBER_PATTERN: str = (
62
+ r'\d+(?:\.\d+)?(?:%|°|km|cm|mm|m|kg|g|lb|ft|in|mph|kmh|hz|mhz|ghz)?'
63
+ )
64
+
65
+ # Quote and bracket pairs
66
+ self.QUOTE_PAIRS: Dict[str, str] = {
67
+ '"': '"', "'": "'", '"': '"', "「": "」", "『": "』",
68
+ "«": "»", "‹": "›", "'": "'", "‚": "'"
69
+ }
70
+
71
+ self.BRACKETS: Dict[str, str] = {
72
+ '(': ')', '[': ']', '{': '}', '⟨': '⟩', '「': '」',
73
+ '『': '』', '【': '】', '〖': '〗', '「': '」'
74
+ }
75
+
76
+ # Compile regex patterns
77
+ self._compile_patterns()
78
+
79
+ def _compile_patterns(self) -> None:
80
+ """Compile regex patterns for better performance."""
81
+ # Pattern for finding potential sentence boundaries
82
+ self.SENTENCE_END: Pattern = re.compile(
83
+ r'''
84
+ # Group for sentence endings
85
+ (?:
86
+ # Standard endings with optional quotes/brackets
87
+ (?<=[.!?])[\"\'\)\]\}»›」』\s]*
88
+
89
+ # Ellipsis
90
+ |(?:\.{2,}|…)
91
+
92
+ # Asian-style endings
93
+ |(?<=[。!?」』】\s])
94
+ )
95
+
96
+ # Must be followed by whitespace and capital letter or number
97
+ (?=\s+(?:[A-Z0-9]|["'({[\[「『《‹〈][A-Z]))
98
+ ''',
99
+ re.VERBOSE
100
+ )
101
+
102
+ # Pattern for abbreviations
103
+ abbrev_pattern = '|'.join(re.escape(abbr) for abbr in self.all_abbreviations)
104
+ self.ABBREV_PATTERN: Pattern = re.compile(
105
+ fr'\b(?:{abbrev_pattern})\.?',
106
+ re.IGNORECASE
107
+ )
108
+
109
+ def tokenize(self, text: str) -> List[str]:
110
+ """Split text into sentences while handling complex cases."""
111
+ if not text or not text.strip():
112
+ return []
113
+
114
+ # Initial split on potential sentence boundaries
115
+ sentences = self.SENTENCE_END.split(text)
116
+
117
+ # Clean and validate sentences
118
+ final_sentences = []
119
+ for sentence in sentences:
120
+ sentence = sentence.strip()
121
+ if sentence:
122
+ final_sentences.append(sentence)
123
+
124
+ return final_sentences
125
+
126
+
127
+ class WordTokenizer:
128
+ """Simple but effective word tokenizer with support for contractions and special cases."""
129
+
130
+ def __init__(self):
131
+ self.contractions = {
132
+ "n't": "not", "'ll": "will", "'re": "are", "'s": "is",
133
+ "'m": "am", "'ve": "have", "'d": "would"
134
+ }
135
+
136
+ self.word_pattern = re.compile(r"""
137
+ (?:[A-Za-z]+(?:[''][A-Za-z]+)*)| # Words with optional internal apostrophes
138
+ (?:\d+(?:,\d{3})*(?:\.\d+)?)| # Numbers with commas and decimals
139
+ (?:[@#]?\w+)| # Hashtags and mentions
140
+ (?:[^\w\s]) # Punctuation and symbols
141
+ """, re.VERBOSE)
142
+
143
+ def tokenize(self, text: str) -> List[str]:
144
+ """Split text into words while handling contractions and special cases."""
145
+ tokens = []
146
+ for match in self.word_pattern.finditer(text):
147
+ word = match.group()
148
+ # Handle contractions
149
+ for contraction, expansion in self.contractions.items():
150
+ if word.endswith(contraction):
151
+ base = word[:-len(contraction)]
152
+ if base:
153
+ tokens.append(base)
154
+ tokens.append(expansion)
155
+ break
156
+ else:
157
+ tokens.append(word)
158
+ return tokens
@@ -1,182 +0,0 @@
1
- import json
2
- import httpx
3
- from bs4 import BeautifulSoup
4
- from typing import List, Dict
5
- from webscout import GoogleS, GEMINIAPI
6
- import re
7
- from concurrent.futures import ThreadPoolExecutor, as_completed
8
-
9
-
10
- class WebSearchAgent:
11
- def __init__(self):
12
- self.webs = GoogleS()
13
- self.ai = GEMINIAPI(is_conversation=False, api_key='AIzaSyAYlT5-V0MXZwaLYpXCF1Z-Yvy_tx1jylA')
14
-
15
- def generate_search_queries(self, information: str, num_queries: int = 10) -> List[str]:
16
- prompt = f""" Task: Generate exactly {num_queries} optimal search queries based on the given information.
17
- Instructions:
18
- 1. Analyze the provided information thoroughly.
19
- 2. Identify key concepts, entities, and relationships.
20
- 3. Formulate {num_queries} concise and specific search queries that will yield relevant and diverse results.
21
- 4. Each query should focus on a different aspect or angle of the information.
22
- 5. The queries should be in natural language, not in the form of keywords.
23
- 6. Avoid unnecessary words or phrases that might limit the search results.
24
- 7. **Important**: Return the response **ONLY** in JSON format without any additional text or code blocks.
25
- Your response must be in the following JSON format: {{
26
- "search_queries": [
27
- "Your first search query here",
28
- "Your second search query here",
29
- "...",
30
- "Your last search query here"
31
- ]
32
- }}
33
- Ensure that:
34
- - You provide exactly {num_queries} search queries.
35
- - Each query is unique and focuses on a different aspect of the information.
36
- - The queries are in plain text, suitable for a web search engine.
37
-
38
- Information to base the search queries on:
39
- {information}
40
-
41
- Now, generate the optimal search queries: """
42
-
43
- response = ""
44
- for chunk in self.ai.chat(prompt):
45
- response += chunk
46
-
47
- json_match = re.search(r'\{.*\}', response, re.DOTALL)
48
- if json_match:
49
- json_str = json_match.group(0)
50
- try:
51
- json_response = json.loads(json_str)
52
- print(json_response['search_queries'])
53
- return json_response["search_queries"]
54
- except json.JSONDecodeError:
55
- pass
56
-
57
- queries = re.findall(r'"([^"]+)"', response)
58
- if len(queries) >= num_queries:
59
- return queries[:num_queries]
60
- elif queries:
61
- return queries
62
- else:
63
- return [information]
64
-
65
- def search(self, information: str, region: str = 'wt-wt', safe: str = 'off',
66
- max_results: int = 10) -> List[Dict]:
67
- search_queries = self.generate_search_queries(information, num_queries=10)
68
- all_results = []
69
-
70
- for query in search_queries:
71
- results = []
72
- with self.webs as webs:
73
- for result in webs.search(query, region=region, safe=safe,
74
- max_results=max_results):
75
- results.append(result)
76
- all_results.extend(results)
77
-
78
- return all_results
79
-
80
- def extract_urls(self, results: List[Dict]) -> List[str]:
81
- urls = [result.get('href') for result in results if result.get('href')]
82
- unique_urls = list(set(urls))
83
- return unique_urls
84
-
85
- def fetch_webpage(self, url: str) -> Dict[str, str]:
86
- try:
87
- with httpx.Client(timeout=120) as client:
88
- response = client.get(url)
89
- if response.status_code == 200:
90
- html = response.text
91
- soup = BeautifulSoup(html, 'html.parser')
92
- paragraphs = soup.find_all('p')
93
- text = ' '.join([p.get_text() for p in paragraphs])
94
- words = text.split()
95
- if len(words) > 600:
96
- text = ' '.join(words[:600]) + '...'
97
- return {"url": url, "content": text}
98
- else:
99
- return {"url": url, "content": f"Failed to fetch {url}: HTTP {response.status_code}"}
100
- except Exception as e:
101
- return {"url": url, "content": f"Error fetching {url}: {str(e)}"}
102
-
103
- def fetch_all_webpages(self, urls: List[str], max_workers: int = 10) -> List[Dict[str, str]]:
104
- contents = []
105
- with ThreadPoolExecutor(max_workers=max_workers) as executor:
106
- future_to_url = {executor.submit(self.fetch_webpage, url): url for url in urls}
107
- for future in as_completed(future_to_url):
108
- result = future.result()
109
- contents.append(result)
110
- return contents
111
-
112
-
113
- class OnlineSearcher:
114
- def __init__(self):
115
- self.agent = WebSearchAgent()
116
- self.ai = GEMINIAPI(is_conversation=False, api_key='GOOGLE GEMINI API')
117
-
118
- def answer_question(self, question: str) -> None:
119
- search_results = self.agent.search(question, max_results=10)
120
- urls = self.agent.extract_urls(search_results)
121
- webpage_contents = self.agent.fetch_all_webpages(urls)
122
-
123
- context = "Web search results and extracted content:\n\n"
124
- for i, result in enumerate(search_results, 1):
125
- title = result.get('title', 'No Title')
126
- href = result.get('href', 'No URL')
127
- snippet = result.get('body', 'No Snippet')
128
- context += f"{i}. **Title:** {title}\n **URL:** {href}\n **Snippet:** {snippet}\n\n"
129
-
130
- context += "Extracted webpage contents:\n"
131
- for i, webpage in enumerate(webpage_contents, 1):
132
- content = webpage['content']
133
- content_preview = content[:600] + '...' if len(content) > 600 else content
134
- context += f"{i}. **URL:** {webpage['url']}\n **Content:** {content_preview}\n\n"
135
-
136
- prompt = f""" Task: Provide a comprehensive, insightful, and well-structured answer to the given question based on the provided web search results and your general knowledge.
137
- Question: {question}
138
- Context: {context}
139
- Instructions:
140
- 1. Carefully analyze the provided web search results and extracted content.
141
- 2. Synthesize the information to form a coherent and comprehensive answer.
142
- 3. If the search results contain relevant information, incorporate it into your answer seamlessly.
143
- 4. Avoid providing irrelevant information, and do not reference "according to web page".
144
- 5. If the search results don't contain sufficient information, clearly state this and provide the best answer based on your general knowledge.
145
- 6. Ensure your answer is well-structured, factual, and directly addresses the question.
146
- 7. Use clear headings, bullet points, or other formatting tools to enhance readability where appropriate.
147
- 8. Strive for a tone and style similar to that of professional, authoritative sources like Perplexity, ensuring clarity and depth in your response.
148
- Your response should be informative, accurate, and properly sourced when possible. Begin your answer now: """
149
-
150
- for chunk in self.ai.chat(prompt, stream=True):
151
- print(chunk, end='', flush=True)
152
-
153
-
154
-
155
- # Usage example
156
- if __name__ == "__main__":
157
- assistant = OnlineSearcher()
158
- while True:
159
- try:
160
- question = input(">>> ")
161
- if question.lower() == 'quit':
162
- break
163
- print("=" * 50)
164
- assistant.answer_question(question)
165
- print("=" * 50)
166
- except KeyboardInterrupt:
167
- print("\nExiting.")
168
- break
169
- except Exception as e:
170
- print(f"An error occurred: {e}")
171
-
172
- """
173
- def format_prompt(messages: Messages, add_special_tokens=False) -> str:
174
-
175
- if not add_special_tokens and len(messages) <= 1:
176
- return messages[0]["content"]
177
- formatted = "\n".join([
178
- f'{message["role"].capitalize()}: {message["content"]}'
179
- for message in messages
180
- ])
181
- return f"{formatted}\nAssistant:
182
- """
@@ -1,2 +0,0 @@
1
- from .Onlinesearcher import *
2
- from .functioncall import *