webscout 6.6__py3-none-any.whl → 6.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.

@@ -1,176 +0,0 @@
1
- import requests
2
- import json
3
- from typing import Any, Dict, Optional, Generator, List
4
-
5
- from webscout.AIutel import Optimizers
6
- from webscout.AIutel import Conversation
7
- from webscout.AIutel import AwesomePrompts
8
- from webscout.AIbase import Provider
9
- from webscout import exceptions
10
-
11
-
12
- class Mhystical(Provider):
13
- """
14
- A class to interact with the Mhystical API. Improved to meet webscout provider standards.
15
- """
16
-
17
- AVAILABLE_MODELS = ["gpt-4", "gpt-3.5-turbo"] # Add available models
18
-
19
- def __init__(
20
- self,
21
- is_conversation: bool = True,
22
- max_tokens: int = 2048,
23
- timeout: int = 30,
24
- intro: str = None,
25
- filepath: str = None,
26
- update_file: bool = True,
27
- proxies: dict = {},
28
- history_offset: int = 10250,
29
- act: str = None,
30
- model: str = "gpt-4", # Default model
31
- system_prompt: str = "You are a helpful AI assistant." # Default system prompt
32
- ):
33
- """Initializes the Mhystical API."""
34
- if model not in self.AVAILABLE_MODELS:
35
- raise ValueError(f"Invalid model: {model}. Choose from: {self.AVAILABLE_MODELS}")
36
-
37
- self.session = requests.Session()
38
- self.is_conversation = is_conversation
39
- self.max_tokens_to_sample = max_tokens
40
- self.api_endpoint = "https://api.mhystical.cc/v1/completions"
41
- self.timeout = timeout
42
- self.last_response = {}
43
- self.model = model
44
- self.system_prompt = system_prompt # Store system prompt
45
- self.headers = {
46
- "x-api-key": "mhystical", # Set API key in header (or better, in __init__ from parameter)
47
- "Content-Type": "application/json",
48
- "accept": "*/*",
49
- "user-agent": "Mozilla/5.0"
50
- }
51
- self.__available_optimizers = (
52
- method
53
- for method in dir(Optimizers)
54
- if callable(getattr(Optimizers, method)) and not method.startswith("__")
55
- )
56
- Conversation.intro = (
57
- AwesomePrompts().get_act(
58
- act, raise_not_found=True, default=None, case_insensitive=True
59
- )
60
- if act
61
- else intro or Conversation.intro
62
- )
63
- self.conversation = Conversation(
64
- is_conversation, self.max_tokens_to_sample, filepath, update_file
65
- )
66
- self.conversation.history_offset = history_offset
67
- self.session.proxies = proxies
68
-
69
-
70
- def ask(
71
- self,
72
- prompt: str,
73
- stream: bool = False,
74
- raw: bool = False,
75
- optimizer: str = None,
76
- conversationally: bool = False,
77
- ) -> Dict[str, Any] | Generator[Dict[str, Any], None, None]:
78
-
79
- conversation_prompt = self.conversation.gen_complete_prompt(prompt)
80
- if optimizer:
81
- if optimizer in self.__available_optimizers:
82
- conversation_prompt = getattr(Optimizers, optimizer)(
83
- conversation_prompt if conversationally else prompt
84
- )
85
- else:
86
- raise exceptions.FailedToGenerateResponseError(
87
- f"Optimizer is not one of {self.__available_optimizers}"
88
- )
89
-
90
- messages = [
91
- {"role": "system", "content": self.system_prompt}, # Include system prompt
92
- {"role": "user", "content": conversation_prompt},
93
- ]
94
-
95
- data = {
96
- "model": self.model, # Now using self.model
97
- "messages": messages # Pass messages to API
98
- }
99
-
100
- def for_stream():
101
- try:
102
- with requests.post(self.api_endpoint, headers=self.headers, json=data, stream=True, timeout=self.timeout) as response:
103
- response.raise_for_status() # Raise exceptions for HTTP errors
104
-
105
- # Emulate streaming for this API
106
- full_response = "" # Accumulate the full response
107
- for chunk in response.iter_content(decode_unicode=True, chunk_size=self.stream_chunk_size):
108
- if chunk:
109
- full_response += chunk
110
- yield chunk if raw else {"text": chunk}
111
-
112
- self.last_response.update({"text": full_response})
113
- self.conversation.update_chat_history(prompt, full_response)
114
- except requests.exceptions.RequestException as e:
115
- raise exceptions.ProviderConnectionError(f"Network error: {str(e)}")
116
-
117
- def for_non_stream():
118
- try:
119
- response = self.session.post(self.api_endpoint, headers=self.headers, json=data, timeout=self.timeout)
120
- response.raise_for_status()
121
-
122
- full_response = self._parse_response(response.text)
123
- self.last_response.update({"text": full_response})
124
-
125
- # Yield the entire response as a single chunk
126
- yield {"text": full_response}
127
-
128
- except requests.exceptions.RequestException as e:
129
- raise exceptions.ProviderConnectionError(f"Network error: {str(e)}")
130
-
131
- return for_stream() if stream else for_non_stream()
132
-
133
-
134
-
135
- def chat(
136
- self,
137
- prompt: str,
138
- stream: bool = False,
139
- optimizer: str = None,
140
- conversationally: bool = False,
141
- ) -> str | Generator[str, None, None]:
142
-
143
- def for_stream():
144
- for response in self.ask(
145
- prompt, stream=True, optimizer=optimizer, conversationally=conversationally
146
- ):
147
- yield self.get_message(response)
148
-
149
- def for_non_stream():
150
- response = next(self.ask(
151
- prompt, stream=False, optimizer=optimizer, conversationally=conversationally
152
- ))
153
- return self.get_message(response)
154
- return for_stream() if stream else for_non_stream()
155
-
156
-
157
-
158
- def get_message(self, response: dict) -> str:
159
- assert isinstance(response, dict), "Response should be of dict data-type only"
160
- return response["text"]
161
-
162
- @staticmethod
163
- def _parse_response(response_text: str) -> str:
164
- """Parse and validate API response."""
165
- try:
166
- data = json.loads(response_text)
167
- return data["choices"][0]["message"]["content"].strip()
168
- except (json.JSONDecodeError, KeyError, IndexError) as e:
169
- raise exceptions.InvalidResponseError(f"Failed to parse response: {str(e)}")
170
-
171
- if __name__ == "__main__":
172
- from rich import print
173
- ai = Mhystical()
174
- response = ai.chat(input(">>> "))
175
- for chunk in response:
176
- print(chunk, end="", flush=True)
webstoken/t.py DELETED
@@ -1,75 +0,0 @@
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}")
File without changes