webscout 7.1__py3-none-any.whl → 7.2__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 (144) 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 +20 -0
  24. webscout/Litlogger/core/logger.py +123 -0
  25. webscout/Litlogger/handlers/__init__.py +12 -0
  26. webscout/Litlogger/handlers/console.py +50 -0
  27. webscout/Litlogger/handlers/file.py +143 -0
  28. webscout/Litlogger/handlers/network.py +174 -0
  29. webscout/Litlogger/styles/__init__.py +7 -0
  30. webscout/Litlogger/styles/colors.py +231 -0
  31. webscout/Litlogger/styles/formats.py +377 -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/Blackboxai.py +3 -3
  38. webscout/Provider/ChatGPTGratis.py +226 -0
  39. webscout/Provider/Cloudflare.py +3 -4
  40. webscout/Provider/DeepSeek.py +218 -0
  41. webscout/Provider/Deepinfra.py +3 -3
  42. webscout/Provider/Free2GPT.py +131 -124
  43. webscout/Provider/Gemini.py +100 -115
  44. webscout/Provider/Glider.py +3 -3
  45. webscout/Provider/Groq.py +5 -1
  46. webscout/Provider/Jadve.py +3 -3
  47. webscout/Provider/Marcus.py +191 -192
  48. webscout/Provider/Netwrck.py +3 -3
  49. webscout/Provider/PI.py +2 -2
  50. webscout/Provider/PizzaGPT.py +2 -3
  51. webscout/Provider/QwenLM.py +311 -0
  52. webscout/Provider/TTI/AiForce/__init__.py +22 -22
  53. webscout/Provider/TTI/AiForce/async_aiforce.py +257 -257
  54. webscout/Provider/TTI/AiForce/sync_aiforce.py +242 -242
  55. webscout/Provider/TTI/Nexra/__init__.py +22 -22
  56. webscout/Provider/TTI/Nexra/async_nexra.py +286 -286
  57. webscout/Provider/TTI/Nexra/sync_nexra.py +258 -258
  58. webscout/Provider/TTI/PollinationsAI/__init__.py +23 -23
  59. webscout/Provider/TTI/PollinationsAI/async_pollinations.py +330 -330
  60. webscout/Provider/TTI/PollinationsAI/sync_pollinations.py +285 -285
  61. webscout/Provider/TTI/artbit/__init__.py +22 -22
  62. webscout/Provider/TTI/artbit/async_artbit.py +184 -184
  63. webscout/Provider/TTI/artbit/sync_artbit.py +176 -176
  64. webscout/Provider/TTI/blackbox/__init__.py +4 -4
  65. webscout/Provider/TTI/blackbox/async_blackbox.py +212 -212
  66. webscout/Provider/TTI/blackbox/sync_blackbox.py +199 -199
  67. webscout/Provider/TTI/deepinfra/__init__.py +4 -4
  68. webscout/Provider/TTI/deepinfra/async_deepinfra.py +227 -227
  69. webscout/Provider/TTI/deepinfra/sync_deepinfra.py +199 -199
  70. webscout/Provider/TTI/huggingface/__init__.py +22 -22
  71. webscout/Provider/TTI/huggingface/async_huggingface.py +199 -199
  72. webscout/Provider/TTI/huggingface/sync_huggingface.py +195 -195
  73. webscout/Provider/TTI/imgninza/__init__.py +4 -4
  74. webscout/Provider/TTI/imgninza/async_ninza.py +214 -214
  75. webscout/Provider/TTI/imgninza/sync_ninza.py +209 -209
  76. webscout/Provider/TTI/talkai/__init__.py +4 -4
  77. webscout/Provider/TTI/talkai/async_talkai.py +229 -229
  78. webscout/Provider/TTI/talkai/sync_talkai.py +207 -207
  79. webscout/Provider/TTS/deepgram.py +182 -182
  80. webscout/Provider/TTS/elevenlabs.py +136 -136
  81. webscout/Provider/TTS/gesserit.py +150 -150
  82. webscout/Provider/TTS/murfai.py +138 -138
  83. webscout/Provider/TTS/parler.py +133 -134
  84. webscout/Provider/TTS/streamElements.py +360 -360
  85. webscout/Provider/TTS/utils.py +280 -280
  86. webscout/Provider/TTS/voicepod.py +116 -116
  87. webscout/Provider/TextPollinationsAI.py +2 -3
  88. webscout/Provider/WiseCat.py +193 -0
  89. webscout/Provider/__init__.py +144 -134
  90. webscout/Provider/cerebras.py +242 -227
  91. webscout/Provider/chatglm.py +204 -204
  92. webscout/Provider/dgaf.py +2 -3
  93. webscout/Provider/gaurish.py +2 -3
  94. webscout/Provider/geminiapi.py +208 -208
  95. webscout/Provider/granite.py +223 -0
  96. webscout/Provider/hermes.py +218 -218
  97. webscout/Provider/llama3mitril.py +179 -179
  98. webscout/Provider/llamatutor.py +3 -3
  99. webscout/Provider/llmchat.py +2 -3
  100. webscout/Provider/meta.py +794 -794
  101. webscout/Provider/multichat.py +331 -331
  102. webscout/Provider/typegpt.py +359 -359
  103. webscout/Provider/yep.py +2 -2
  104. webscout/__main__.py +5 -5
  105. webscout/cli.py +319 -319
  106. webscout/conversation.py +241 -242
  107. webscout/exceptions.py +328 -328
  108. webscout/litagent/__init__.py +28 -28
  109. webscout/litagent/agent.py +2 -3
  110. webscout/litprinter/__init__.py +0 -58
  111. webscout/scout/__init__.py +8 -8
  112. webscout/scout/core.py +884 -884
  113. webscout/scout/element.py +459 -459
  114. webscout/scout/parsers/__init__.py +69 -69
  115. webscout/scout/parsers/html5lib_parser.py +172 -172
  116. webscout/scout/parsers/html_parser.py +236 -236
  117. webscout/scout/parsers/lxml_parser.py +178 -178
  118. webscout/scout/utils.py +38 -38
  119. webscout/swiftcli/__init__.py +811 -811
  120. webscout/update_checker.py +2 -12
  121. webscout/version.py +1 -1
  122. webscout/webscout_search.py +5 -4
  123. webscout/zeroart/__init__.py +54 -54
  124. webscout/zeroart/base.py +60 -60
  125. webscout/zeroart/effects.py +99 -99
  126. webscout/zeroart/fonts.py +816 -816
  127. {webscout-7.1.dist-info → webscout-7.2.dist-info}/METADATA +4 -3
  128. webscout-7.2.dist-info/RECORD +217 -0
  129. webstoken/__init__.py +30 -30
  130. webstoken/classifier.py +189 -189
  131. webstoken/keywords.py +216 -216
  132. webstoken/language.py +128 -128
  133. webstoken/ner.py +164 -164
  134. webstoken/normalizer.py +35 -35
  135. webstoken/processor.py +77 -77
  136. webstoken/sentiment.py +206 -206
  137. webstoken/stemmer.py +73 -73
  138. webstoken/tagger.py +60 -60
  139. webstoken/tokenizer.py +158 -158
  140. webscout-7.1.dist-info/RECORD +0 -198
  141. {webscout-7.1.dist-info → webscout-7.2.dist-info}/LICENSE.md +0 -0
  142. {webscout-7.1.dist-info → webscout-7.2.dist-info}/WHEEL +0 -0
  143. {webscout-7.1.dist-info → webscout-7.2.dist-info}/entry_points.txt +0 -0
  144. {webscout-7.1.dist-info → webscout-7.2.dist-info}/top_level.txt +0 -0
@@ -1,681 +1,67 @@
1
- import os
2
- import sys
3
- import json
4
- import threading
5
- import datetime
6
- from enum import Enum
7
- from pathlib import Path
8
- from typing import Optional, Union, Dict, Any, Tuple
9
-
10
- class TextStyle:
11
- """Text styling options"""
12
- BOLD = "\033[1m"
13
- DIM = "\033[2m"
14
- ITALIC = "\033[3m"
15
- UNDERLINE = "\033[4m"
16
- BLINK = "\033[5m"
17
- REVERSE = "\033[7m"
18
- HIDDEN = "\033[8m"
19
- STRIKE = "\033[9m"
20
- DOUBLE_UNDERLINE = "\033[21m"
21
- OVERLINE = "\033[53m"
22
- RESET = "\033[0m"
23
-
24
- class LogFormat:
25
- """Pre-defined log formats with beautiful styling
26
-
27
- Examples:
28
- >>> logger = LitLogger(format=LogFormat.MODERN_EMOJI)
29
- >>> logger.info("Server started") # [2024-01-20 15:30:45] Server started
30
-
31
- >>> logger = LitLogger(format=LogFormat.RAINBOW_BOX)
32
- >>> logger.warning("High CPU") # Shows warning in a rainbow-colored box
33
- """
34
-
35
- # Basic Formats
36
- MINIMAL = "[{time}] {level} {message}"
37
- STANDARD = "[{time}] {level} {name}: {message}"
38
- DETAILED = "[{time}] {level} {name} [{file}:{line}] >>> {message}"
39
-
40
- # Modern Styles
41
- MODERN = " {time} | {level} | {name} | {message}"
42
- MODERN_EMOJI = "{emoji} [{time}] {level} {message}"
43
- MODERN_CLEAN = "{time} {level} {message}"
44
- MODERN_BRACKET = "【{time}】「{level}」{message}"
45
-
46
- # Boxed Styles
47
- BOXED = """
48
- ╭─────────────────────╮
49
- │ [{time}]
50
- {level} - {name}
51
- │ {message}
52
- ╰─────────────────────╯"""
53
-
54
- DOUBLE_BOX = """
55
- ╔══════════════════════╗
56
- {level} @ {time}
57
- ║ {name}
58
- ║ {message}
59
- ╚══════════════════════╝"""
60
-
61
- ROUNDED_BOX = """
62
- ╭──────────────────────╮
63
- │ {time} • {level}
64
- ├──────────────────────┤
65
- │ {message}
66
- ╰──────────────────────╯"""
67
-
68
- RAINBOW_BOX = """
69
- {level} - {time}
70
- {name}: {message}
71
- """
72
-
73
- # Debug & Development
74
- DEBUG = "[{time}] {level} {name} ({file}:{line}) {message}"
75
- DEBUG_FULL = """
76
- ┌─ Debug Info ─┐
77
- │ Time: {time}
78
- │ Level: {level}
79
- │ Name: {name}
80
- │ File: {file}:{line}
81
- │ Message: {message}
82
- └──────────────┘"""
83
-
84
- TRACE = """
85
- Trace Details:
86
- Time: {time}
87
- Level: {level}
88
- Location: {file}:{line}
89
- Message: {message}"""
90
-
91
- # Error Formats
92
- ERROR = "!!! {level} !!! [{time}] {name} - {message}"
93
- ERROR_DETAILED = """
94
- {level} ALERT
95
- Time: {time}
96
- Component: {name}
97
- Location: {file}:{line}
98
- Message: {message}"""
99
-
100
- ERROR_COMPACT = " [{time}] {level}: {message}"
101
-
102
- # Status & Progress
103
- STATUS = """
104
- Status Update:
105
- Time: {time}
106
- Level: {level}
107
- Component: {name}
108
- Message: {message}"""
109
-
110
- PROGRESS = """
111
- [{time}] Progress Report
112
- ├─ Level: {level}
113
- ├─ Component: {name}
114
- └─ Status: {message}"""
115
-
116
- # Network & API
117
- HTTP = """
118
- API {level} [{time}]
119
- Endpoint: {name}
120
- Response: {message}"""
121
-
122
- REQUEST = """
123
- → Incoming Request
124
- Time: {time}
125
- Level: {level}
126
- API: {name}
127
- Details: {message}"""
128
-
129
- RESPONSE = """
130
- ← Outgoing Response
131
- Time: {time}
132
- Level: {level}
133
- API: {name}
134
- Details: {message}"""
135
-
136
- # System & Metrics
137
- SYSTEM = """
138
- System Event
139
- {time}
140
- {level}
141
- {name}
142
- {message}"""
143
-
144
- METRIC = """
145
- Metric Report [{time}]
146
- Level: {level}
147
- Source: {name}
148
- Value: {message}"""
149
-
150
- # Security & Audit
151
- SECURITY = """
152
- Security Event
153
- Time: {time}
154
- Level: {level}
155
- Source: {name}
156
- Event: {message}"""
157
-
158
- AUDIT = """
159
- Audit Log Entry
160
- Time: {time}
161
- Level: {level}
162
- Component: {name}
163
- Action: {message}"""
164
-
165
- # Special Formats
166
- RAINBOW = " {time} {level} {message}"
167
- MINIMAL_EMOJI = "{emoji} {message}"
168
- TIMESTAMP = "{time} {message}"
169
- COMPONENT = "[{name}] {message}"
170
-
171
- # JSON Format (for machine parsing)
172
- JSON = '{{"time":"{time}","level":"{level}","name":"{name}","message":"{message}"}}'
173
-
174
- # XML Format
175
- XML = """<log>
176
- <time>{time}</time>
177
- <level>{level}</level>
178
- <name>{name}</name>
179
- <message>{message}</message>
180
- </log>"""
181
-
182
- # Markdown Format
183
- MARKDOWN = """
184
- ## Log Entry
185
- - **Time:** {time}
186
- - **Level:** {level}
187
- - **Component:** {name}
188
- - **Message:** {message}
189
- """
190
-
191
- class ColorScheme:
192
- """Pre-defined color schemes with rich, carefully crafted color palettes
193
-
194
- Examples:
195
- >>> logger = LitLogger(color_scheme=ColorScheme.CYBERPUNK)
196
- >>> logger.info("Neon city lights...")
197
- >>>
198
- >>> logger = LitLogger(color_scheme=ColorScheme.AURORA)
199
- >>> logger.warning("Northern lights warning")
200
- """
201
-
202
- # Cyberpunk theme with neon colors
203
- CYBERPUNK = {
204
- "trace": (128, 128, 255), # Neon blue
205
- "debug": (255, 0, 255), # Hot pink
206
- "info": (0, 255, 255), # Cyan
207
- "success": (0, 255, 128), # Neon green
208
- "warning": (255, 128, 0), # Neon orange
209
- "error": (255, 0, 128), # Magenta
210
- "critical": (255, 0, 0) # Bright red
211
- }
212
-
213
- # Matrix-inspired green theme
214
- MATRIX = {
215
- "trace": (0, 100, 0), # Dark green
216
- "debug": (0, 150, 0), # Medium green
217
- "info": (0, 200, 0), # Bright green
218
- "success": (0, 255, 0), # Pure green
219
- "warning": (200, 255, 0), # Yellow-green
220
- "error": (255, 200, 0), # Orange-green
221
- "critical": (255, 0, 0) # Red alert
222
- }
223
-
224
- # Ocean depths theme
225
- OCEAN = {
226
- "trace": (70, 130, 180), # Steel blue
227
- "debug": (100, 149, 237), # Cornflower blue
228
- "info": (0, 191, 255), # Deep sky blue
229
- "success": (127, 255, 212),# Aquamarine
230
- "warning": (255, 215, 0), # Gold
231
- "error": (255, 69, 0), # Red-orange
232
- "critical": (255, 0, 0) # Pure red
233
- }
234
-
235
- # Aurora borealis inspired
236
- AURORA = {
237
- "trace": (80, 200, 120), # Soft green
238
- "debug": (45, 149, 237), # Arctic blue
239
- "info": (148, 87, 235), # Purple aurora
240
- "success": (0, 255, 170), # Northern lights
241
- "warning": (255, 128, 255),# Pink aurora
242
- "error": (255, 70, 120), # Rose red
243
- "critical": (255, 0, 80) # Deep pink
244
- }
245
-
246
- # Sunset gradient
247
- SUNSET = {
248
- "trace": (255, 155, 0), # Golden hour
249
- "debug": (255, 122, 92), # Coral
250
- "info": (255, 89, 100), # Sunset pink
251
- "success": (255, 166, 0), # Amber
252
- "warning": (255, 99, 72), # Tomato
253
- "error": (255, 55, 55), # Sunset red
254
- "critical": (255, 0, 55) # Deep sunset
255
- }
256
-
257
- # Retro computing
258
- RETRO = {
259
- "trace": (170, 170, 170), # Light gray
260
- "debug": (0, 187, 0), # Phosphor green
261
- "info": (187, 187, 0), # Amber
262
- "success": (0, 255, 0), # Bright green
263
- "warning": (255, 187, 0), # Yellow
264
- "error": (255, 85, 85), # Light red
265
- "critical": (255, 0, 0) # Bright red
266
- }
267
-
268
- # Pastel dream
269
- PASTEL = {
270
- "trace": (173, 216, 230), # Light blue
271
- "debug": (221, 160, 221), # Plum
272
- "info": (176, 224, 230), # Powder blue
273
- "success": (144, 238, 144),# Light green
274
- "warning": (255, 218, 185),# Peach
275
- "error": (255, 182, 193), # Light pink
276
- "critical": (255, 192, 203)# Pink
277
- }
278
-
279
- # Monochrome elegance
280
- MONO = {
281
- "trace": (128, 128, 128), # Gray
282
- "debug": (160, 160, 160), # Light gray
283
- "info": (192, 192, 192), # Silver
284
- "success": (224, 224, 224),# Light silver
285
- "warning": (96, 96, 96), # Dark gray
286
- "error": (64, 64, 64), # Darker gray
287
- "critical": (32, 32, 32) # Almost black
288
- }
289
-
290
- # Forest theme
291
- FOREST = {
292
- "trace": (95, 158, 160), # Cadet blue
293
- "debug": (85, 107, 47), # Dark olive
294
- "info": (34, 139, 34), # Forest green
295
- "success": (50, 205, 50), # Lime green
296
- "warning": (218, 165, 32), # Golden rod
297
- "error": (178, 34, 34), # Firebrick
298
- "critical": (139, 0, 0) # Dark red
299
- }
300
-
301
- # Deep space
302
- SPACE = {
303
- "trace": (25, 25, 112), # Midnight blue
304
- "debug": (72, 61, 139), # Dark slate blue
305
- "info": (138, 43, 226), # Blue violet
306
- "success": (65, 105, 225), # Royal blue
307
- "warning": (255, 215, 0), # Gold
308
- "error": (220, 20, 60), # Crimson
309
- "critical": (178, 34, 34) # Firebrick
310
- }
311
-
312
- class LogLevel(Enum):
313
- """Log levels with their string representations and ANSI colors"""
314
- TRACE = ("TRACE", "trace")
315
- DEBUG = ("DEBUG", "debug")
316
- INFO = ("INFO", "info")
317
- SUCCESS = ("SUCCESS", "success")
318
- WARNING = ("WARNING", "warning")
319
- ERROR = ("ERROR", "error")
320
- CRITICAL = ("CRITICAL", "critical")
321
-
322
- def __init__(self, name: str, color_key: str):
323
- self._name = name
324
- self._color_key = color_key
325
-
326
- def __str__(self) -> str:
327
- return f"[{self._name}]"
328
-
329
- def style(self, style: str, color_scheme: Dict[str, Tuple[int, int, int]]) -> str:
330
- """Apply a text style and color to the log level"""
331
- color = color_scheme.get(self._color_key, (255, 255, 255))
332
- style_code = getattr(TextStyle, style.upper(), "")
333
- return f"{style_code}\033[38;2;{color[0]};{color[1]};{color[2]}m{str(self)}\033[0m"
334
-
335
- def __ge__(self, other):
336
- if not isinstance(other, LogLevel):
337
- return NotImplemented
338
- levels = list(LogLevel)
339
- return levels.index(self) >= levels.index(other)
340
-
341
- class LitLogger:
342
- """A lightweight, colorful logger with style and intelligent level detection
343
-
344
- Examples:
345
- >>> logger = LitLogger()
346
- >>> logger.auto("Starting application...") # INFO
347
- >>> logger.auto("CPU: 95%, Memory: 87%") # WARNING (detected high metrics)
348
- >>> logger.auto("404: Page not found") # ERROR (detected status code)
349
- >>> logger.auto("x = 42, y = [1,2,3]") # DEBUG (detected variable assignment)
350
- """
351
-
352
- # Enhanced level indicators with weighted patterns
353
- LEVEL_INDICATORS = {
354
- LogLevel.ERROR: {
355
- "patterns": [
356
- "error", "exception", "failed", "failure", "critical", "fatal",
357
- "crash", "abort", "terminated", "denied", "invalid", "unauthorized",
358
- "forbidden", "timeout", "unavailable", "offline", "dead", "killed",
359
- r"\b(4[0-9]{2}|5[0-9]{2})\b", # HTTP error codes
360
- r"err\d+", r"error\d+", # Error codes
361
- r"exception\[\d+\]", # Exception references
362
- "null pointer", "undefined", "not found", "missing",
363
- "corruption", "corrupted", "damage", "damaged",
364
- "exploit", "vulnerability", "breach", "attack",
365
- "overflow", "underflow", "deadlock", "race condition"
366
- ],
367
- "weight": 2.0
368
- },
369
- LogLevel.WARNING: {
370
- "patterns": [
371
- "warning", "warn", "caution", "alert", "attention",
372
- "notice", "reminder", "consider", "potential", "possible",
373
- "deprecated", "unstable", "experimental", "beta",
374
- "high", "heavy", "excessive", "threshold", "limit",
375
- "slow", "delayed", "latency", "lag", "bottleneck",
376
- "suspicious", "unusual", "unexpected", "irregular",
377
- "restricted", "limited", "constrained", "reaching",
378
- r"\b8[5-9]%|\b9[0-9]%|100%", # High percentages
379
- r"running low", "almost full", "nearing",
380
- "obsolete", "legacy", "old version", "outdated"
381
- ],
382
- "weight": 1.5
383
- },
384
- LogLevel.SUCCESS: {
385
- "patterns": [
386
- "success", "succeeded", "completed", "done", "ok", "okay",
387
- "passed", "validated", "verified", "confirmed", "approved",
388
- "established", "connected", "synchronized", "ready",
389
- "online", "active", "alive", "running", "operational",
390
- "deployed", "published", "delivered", "achieved",
391
- "fixed", "resolved", "solved", "handled", "processed",
392
- r"2[0-9]{2}", # HTTP success codes
393
- "created", "updated", "modified", "changed", "saved"
394
- ],
395
- "weight": 1.0
396
- },
397
- LogLevel.DEBUG: {
398
- "patterns": [
399
- "debug", "debugging", "trace", "tracing", "verbose",
400
- r"var\s+\w+", r"\w+\s*=\s*[\w\[\{\(]", # Variable assignments
401
- r"checking", "testing", "inspecting", "examining",
402
- "value", "variable", "object", "instance", "type",
403
- "print", "dump", "output", "log", "console",
404
- "step", "phase", "stage", "point", "checkpoint",
405
- r"[\w\.]+\(.*\)", # Function calls
406
- "returned", "received", "got", "fetched", "loaded",
407
- "params", "args", "arguments", "inputs", "outputs"
408
- ],
409
- "weight": 0.8
410
- },
411
- LogLevel.TRACE: {
412
- "patterns": [
413
- "trace", "step", "entering", "exiting", "called",
414
- "begin", "end", "start", "finish", "init",
415
- "enter", "exit", "entry", "return", "returns",
416
- "calling", "called", "invoke", "invoked",
417
- "request", "response", "sending", "receiving",
418
- "open", "close", "opened", "closed",
419
- "load", "unload", "loaded", "unloaded",
420
- "initialize", "initialized", "setup", "cleanup"
421
- ],
422
- "weight": 0.5
423
- }
424
- }
425
-
426
- # Metric thresholds for numerical values
427
- METRIC_THRESHOLDS = {
428
- "critical": {
429
- "patterns": ["cpu", "memory", "ram", "disk", "storage", "load", "usage", "utilization", "error_rate", "failure_rate"],
430
- "threshold": 95,
431
- "level": LogLevel.ERROR
432
- },
433
- "warning": {
434
- "patterns": ["cpu", "memory", "ram", "disk", "storage", "load", "usage", "utilization", "error_rate", "failure_rate"],
435
- "threshold": 80,
436
- "level": LogLevel.WARNING
437
- },
438
- "performance": {
439
- "patterns": ["latency", "delay", "response", "time", "duration", "timeout"],
440
- "threshold": 1000, # milliseconds
441
- "level": LogLevel.WARNING
442
- }
443
- }
444
-
445
- def __init__(self,
446
- name: str = "LitLogger",
447
- log_path: Optional[Union[str, Path]] = None,
448
- console_output: bool = True,
449
- time_format: str = "%Y-%m-%d %H:%M:%S",
450
- level: Optional[str] = None,
451
- format: str = LogFormat.DETAILED,
452
- color_scheme: Dict[str, Tuple[int, int, int]] = ColorScheme.OCEAN,
453
- level_styles: Optional[Dict[str, str]] = None):
454
- """Initialize the logger
455
-
456
- Examples:
457
- >>> # Basic console logger
458
- >>> logger = LitLogger()
459
- >>>
460
- >>> # Customized logger
461
- >>> logger = LitLogger(
462
- ... name="MyApp",
463
- ... format=LogFormat.MODERN,
464
- ... color_scheme=ColorScheme.NEON
465
- ... )
466
- """
467
- self.name = name
468
- self.console_output = console_output
469
- self.time_format = time_format
470
- self.format = format
471
- self.color_scheme = color_scheme
472
- self.level_styles = level_styles or {
473
- "TRACE": "DIM",
474
- "DEBUG": "NORMAL",
475
- "INFO": "NORMAL",
476
- "SUCCESS": "BOLD",
477
- "WARNING": "BOLD",
478
- "ERROR": "BOLD",
479
- "CRITICAL": "BOLD"
480
- }
481
-
482
- try:
483
- self.level = LogLevel[level.upper()] if level else LogLevel.TRACE
484
- except (KeyError, AttributeError):
485
- print(f"Invalid log level: {level}. Using TRACE level.")
486
- self.level = LogLevel.TRACE
487
-
488
- self.log_file = None
489
- if log_path:
490
- try:
491
- self.log_file = Path(log_path)
492
- self.log_file.parent.mkdir(parents=True, exist_ok=True)
493
- except Exception as e:
494
- print(f"Failed to initialize log file at {log_path}: {e}")
495
-
496
- def _format_message(self, level: LogLevel, message: str, **kwargs) -> str:
497
- """Format the log message"""
498
- # Get caller info
499
- frame = sys._getframe(2)
500
- filename = os.path.basename(frame.f_code.co_filename)
501
- line = frame.f_lineno
502
-
503
- # Format time
504
- time_str = datetime.datetime.now().strftime(self.time_format)
505
-
506
- # Format parameters
507
- params = {
508
- 'time': time_str,
509
- 'level': level.style(self.level_styles.get(level._name, "NORMAL"), self.color_scheme),
510
- 'name': self.name,
511
- 'message': message,
512
- 'file': filename,
513
- 'line': line
514
- }
515
-
516
- try:
517
- return self.format.format(**params)
518
- except Exception:
519
- # Fallback to minimal format
520
- return f"[{time_str}] {level.style('NORMAL', self.color_scheme)} {message}"
521
-
522
- def _log(self, level: LogLevel, message: str, **kwargs) -> None:
523
- """Log a message"""
524
- if level >= self.level:
525
- formatted = self._format_message(level, message, **kwargs)
526
-
527
- # Console output
528
- if self.console_output:
529
- print(formatted, flush=True)
530
-
531
- # File output (without ANSI codes)
532
- if self.log_file:
533
- clean_msg = f"[{datetime.datetime.now().strftime(self.time_format)}] [{level._name}] {message}"
534
- if kwargs:
535
- clean_msg += f" Context: {json.dumps(kwargs)}"
536
- try:
537
- with open(self.log_file, 'a', encoding='utf-8') as f:
538
- f.write(clean_msg + '\n')
539
- except Exception as e:
540
- print(f"Failed to write to log file: {e}", flush=True)
541
-
542
- def _detect_level(self, message: str, **kwargs) -> LogLevel:
543
- """Intelligently detect the appropriate log level based on content and context
544
-
545
- Uses advanced pattern matching, metric analysis, and context weighting to determine
546
- the most appropriate log level for any given message.
547
-
548
- Examples:
549
- >>> logger = LitLogger()
550
- >>> logger._detect_level("CPU usage at 96%") # ERROR (critical resource usage)
551
- >>> logger._detect_level("Response time: 1500ms") # WARNING (high latency)
552
- >>> logger._detect_level("x = calculate(y)") # DEBUG (code execution)
553
- >>> logger._detect_level("HTTP 404: Not Found") # ERROR (status code)
554
- """
555
- message_lower = message.lower()
556
-
557
- # Combine message with context for full analysis
558
- context_str = " ".join(f"{k}={v}" for k, v in kwargs.items()).lower()
559
- full_text = f"{message_lower} {context_str}"
560
-
561
- # Initialize score tracking
562
- level_scores = {level: 0.0 for level in LogLevel}
563
-
564
- # Check for numeric metrics
565
- for metric_type, config in self.METRIC_THRESHOLDS.items():
566
- for pattern in config["patterns"]:
567
- if pattern in full_text:
568
- # Extract numbers from the text
569
- import re
570
- numbers = re.findall(r'\d+(?:\.\d+)?', full_text)
571
- for num in numbers:
572
- try:
573
- value = float(num)
574
- if value >= config["threshold"]:
575
- level_scores[config["level"]] += 2.0
576
- except ValueError:
577
- continue
578
-
579
- # Pattern matching with weights
580
- for level, config in self.LEVEL_INDICATORS.items():
581
- weight = config["weight"]
582
- for pattern in config["patterns"]:
583
- import re
584
- if re.search(pattern, full_text, re.IGNORECASE):
585
- level_scores[level] += weight
586
-
587
- # Context analysis
588
- if kwargs:
589
- # Check for error-like status codes
590
- status = kwargs.get("status") or kwargs.get("code") or kwargs.get("http_status")
591
- if status:
592
- try:
593
- status = int(status)
594
- if status >= 400:
595
- level_scores[LogLevel.ERROR] += 2.0
596
- elif status >= 300:
597
- level_scores[LogLevel.WARNING] += 1.5
598
- elif status >= 200:
599
- level_scores[LogLevel.SUCCESS] += 1.0
600
- except (ValueError, TypeError):
601
- pass
602
-
603
- # Get the level with the highest score
604
- max_score = max(level_scores.values())
605
- if max_score > 0:
606
- return max(level_scores.items(), key=lambda x: x[1])[0]
607
-
608
- # Default to INFO if no strong indicators
609
- return LogLevel.INFO
610
-
611
- def auto(self, message: str, **kwargs) -> None:
612
- """Automatically log message with the appropriate level based on content
613
-
614
- Examples:
615
- >>> logger = LitLogger()
616
- >>> logger.auto("Starting application...") # INFO
617
- >>> logger.auto("Warning: Memory usage high", memory=85) # WARNING
618
- >>> logger.auto("Error: Database connection failed") # ERROR
619
- >>> logger.auto("Debug: x = 42", variable="x", value=42) # DEBUG
620
- """
621
- level = self._detect_level(message, **kwargs)
622
- self._log(level, message, **kwargs)
623
-
624
- def trace(self, message: str, **kwargs) -> None:
625
- self._log(LogLevel.TRACE, message, **kwargs)
626
-
627
- def debug(self, message: str, **kwargs) -> None:
628
- self._log(LogLevel.DEBUG, message, **kwargs)
629
-
630
- def info(self, message: str, **kwargs) -> None:
631
- self._log(LogLevel.INFO, message, **kwargs)
632
-
633
- def success(self, message: str, **kwargs) -> None:
634
- self._log(LogLevel.SUCCESS, message, **kwargs)
635
-
636
- def warning(self, message: str, **kwargs) -> None:
637
- self._log(LogLevel.WARNING, message, **kwargs)
638
-
639
- def error(self, message: str, **kwargs) -> None:
640
- self._log(LogLevel.ERROR, message, **kwargs)
641
-
642
- def critical(self, message: str, **kwargs) -> None:
643
- self._log(LogLevel.CRITICAL, message, **kwargs)
644
-
645
- if __name__ == "__main__":
646
- # Test all color schemes
647
- message = "Testing color scheme: {}"
648
- test_name = "ColorTest"
649
-
650
- schemes = [
651
- ("CYBERPUNK", ColorScheme.CYBERPUNK, LogFormat.MODERN),
652
- ("AURORA", ColorScheme.AURORA, LogFormat.BOXED),
653
- ("SUNSET", ColorScheme.SUNSET, LogFormat.ERROR),
654
- ("RETRO", ColorScheme.RETRO, LogFormat.STANDARD),
655
- ("PASTEL", ColorScheme.PASTEL, LogFormat.MINIMAL),
656
- ("MONO", ColorScheme.MONO, LogFormat.DEBUG),
657
- ("FOREST", ColorScheme.FOREST, LogFormat.DETAILED),
658
- ("SPACE", ColorScheme.SPACE, LogFormat.MODERN)
659
- ]
660
-
661
- for scheme_name, scheme, format in schemes:
662
- logger = LitLogger(
663
- name=f"{test_name}_{scheme_name}",
664
- format=format,
665
- color_scheme=scheme
666
- )
667
-
668
- print(f"\n=== Testing {scheme_name} Theme ===")
669
- logger.trace(f"Trace message in {scheme_name}")
670
- logger.debug(f"Debug message in {scheme_name}")
671
- logger.info(f"Info message in {scheme_name}")
672
- logger.success(f"Success message in {scheme_name}")
673
- logger.warning(f"Warning message in {scheme_name}")
674
- logger.error(f"Error message in {scheme_name}")
675
- logger.critical(f"Critical message in {scheme_name}")
676
-
677
- # Test auto-detection with current theme
678
- logger.auto(f"CPU at 96% in {scheme_name}", cpu=96)
679
- logger.auto(f"Checking variables in {scheme_name}", x=42, y="test")
680
- logger.auto(f"HTTP 404 in {scheme_name}", status=404)
681
- print("=" * 40)
1
+ """
2
+ LitLogger - A feature-rich, colorful logging library with intelligent level detection.
3
+
4
+ Features:
5
+ - Colorful console output
6
+ - Multiple output formats including JSON
7
+ - File logging with rotation
8
+ - Network logging (HTTP/HTTPS/TCP)
9
+ - Async logging support
10
+ - Intelligent log level detection
11
+ - Context managers
12
+ - Performance metrics
13
+ - Log aggregation
14
+ """
15
+
16
+ from .core.logger import Logger
17
+ from .core.level import LogLevel
18
+ from .styles.colors import LogColors
19
+ from .styles.formats import LogFormat
20
+ from .styles.text import TextStyle
21
+ from .handlers.console import ConsoleHandler, ErrorConsoleHandler
22
+ from .handlers.file import FileHandler
23
+ from .handlers.network import NetworkHandler
24
+ from .utils.detectors import LevelDetector
25
+ from .utils.formatters import MessageFormatter
26
+
27
+ # Create a default logger instance
28
+ default_logger = Logger(
29
+ name="LitLogger",
30
+ handlers=[ConsoleHandler()]
31
+ )
32
+
33
+ # Expose common logging methods at package level
34
+ debug = default_logger.debug
35
+ info = default_logger.info
36
+ warning = default_logger.warning
37
+ error = default_logger.error
38
+ critical = default_logger.critical
39
+
40
+ __all__ = [
41
+ # Core
42
+ "Logger",
43
+ "LogLevel",
44
+
45
+ # Styles
46
+ "LogColors",
47
+ "LogFormat",
48
+ "TextStyle",
49
+
50
+ # Handlers
51
+ "ConsoleHandler",
52
+ "ErrorConsoleHandler",
53
+ "FileHandler",
54
+ "NetworkHandler",
55
+
56
+ # Utils
57
+ "LevelDetector",
58
+ "MessageFormatter",
59
+
60
+ # Package-level logging functions
61
+ "debug",
62
+ "info",
63
+ "warning",
64
+ "error",
65
+ "critical",
66
+
67
+ ]