Spaces:
Paused
Paused
:gem: [Feature] New logging system
Browse files- conversation_creater.py +13 -15
- logger/__init_.py +0 -0
- logger/logger.py +241 -0
conversation_creater.py
CHANGED
@@ -6,6 +6,7 @@ import pprint
|
|
6 |
import urllib
|
7 |
|
8 |
from chathub_request_constructor import ChathubRequestConstructor
|
|
|
9 |
|
10 |
|
11 |
http_proxy = "http://localhost:11111" # Replace with yours
|
@@ -39,7 +40,7 @@ def serialize_websocket_message(msg: dict) -> str:
|
|
39 |
return json.dumps(msg, ensure_ascii=False) + "\x1e"
|
40 |
|
41 |
|
42 |
-
class
|
43 |
def __init__(
|
44 |
self,
|
45 |
sec_access_token=None,
|
@@ -129,23 +130,20 @@ class ConversationChatter:
|
|
129 |
delta_content_pointer = len(message_html)
|
130 |
|
131 |
if message.get("suggestedResponses"):
|
132 |
-
|
133 |
for suggestion in message.get("suggestedResponses"):
|
134 |
suggestion_text = suggestion.get("text")
|
135 |
-
|
136 |
|
137 |
elif message_type in ["InternalSearchQuery"]:
|
138 |
message_hidden_text = message["hiddenText"]
|
139 |
-
|
140 |
-
f"\n[Searching: [{message_hidden_text}]]",
|
141 |
-
flush=True,
|
142 |
-
)
|
143 |
elif message_type in [
|
144 |
"InternalSearchResult",
|
145 |
]:
|
146 |
-
|
147 |
elif message_type in ["InternalLoaderMessage"]:
|
148 |
-
|
149 |
elif message_type in ["RenderCardRequest"]:
|
150 |
continue
|
151 |
else:
|
@@ -156,12 +154,12 @@ class ConversationChatter:
|
|
156 |
elif data.get("type") == 2:
|
157 |
if data.get("item"):
|
158 |
item = data.get("item")
|
159 |
-
|
160 |
# for message in item.get("messages"):
|
161 |
# author = message["author"]
|
162 |
# message_text = message["text"]
|
163 |
elif data.get("type") == 3:
|
164 |
-
|
165 |
await wss.close()
|
166 |
break
|
167 |
elif data.get("type") == 6:
|
@@ -175,7 +173,7 @@ if __name__ == "__main__":
|
|
175 |
creator = ConversationCreator()
|
176 |
creator.create()
|
177 |
|
178 |
-
|
179 |
sec_access_token=creator.response_headers[
|
180 |
"x-sydney-encryptedconversationsignature"
|
181 |
],
|
@@ -183,8 +181,8 @@ if __name__ == "__main__":
|
|
183 |
conversation_id=creator.response_content["conversationId"],
|
184 |
)
|
185 |
prompt = "Today's weather of California"
|
186 |
-
|
187 |
-
|
188 |
loop = asyncio.get_event_loop()
|
189 |
-
loop.run_until_complete(
|
190 |
loop.close()
|
|
|
6 |
import urllib
|
7 |
|
8 |
from chathub_request_constructor import ChathubRequestConstructor
|
9 |
+
from logger.logger import logger
|
10 |
|
11 |
|
12 |
http_proxy = "http://localhost:11111" # Replace with yours
|
|
|
40 |
return json.dumps(msg, ensure_ascii=False) + "\x1e"
|
41 |
|
42 |
|
43 |
+
class ConversationConnector:
|
44 |
def __init__(
|
45 |
self,
|
46 |
sec_access_token=None,
|
|
|
130 |
delta_content_pointer = len(message_html)
|
131 |
|
132 |
if message.get("suggestedResponses"):
|
133 |
+
logger.note("\nSuggested Questions: ")
|
134 |
for suggestion in message.get("suggestedResponses"):
|
135 |
suggestion_text = suggestion.get("text")
|
136 |
+
logger.mesg(f"- {suggestion_text}")
|
137 |
|
138 |
elif message_type in ["InternalSearchQuery"]:
|
139 |
message_hidden_text = message["hiddenText"]
|
140 |
+
logger.note(f"\n[Searching: [{message_hidden_text}]]")
|
|
|
|
|
|
|
141 |
elif message_type in [
|
142 |
"InternalSearchResult",
|
143 |
]:
|
144 |
+
logger.note("[Analyzing search results ...]")
|
145 |
elif message_type in ["InternalLoaderMessage"]:
|
146 |
+
logger.note("[Generating answers ...]\n")
|
147 |
elif message_type in ["RenderCardRequest"]:
|
148 |
continue
|
149 |
else:
|
|
|
154 |
elif data.get("type") == 2:
|
155 |
if data.get("item"):
|
156 |
item = data.get("item")
|
157 |
+
logger.note("\n[Saving chat messages ...]")
|
158 |
# for message in item.get("messages"):
|
159 |
# author = message["author"]
|
160 |
# message_text = message["text"]
|
161 |
elif data.get("type") == 3:
|
162 |
+
logger.success("[Finished]")
|
163 |
await wss.close()
|
164 |
break
|
165 |
elif data.get("type") == 6:
|
|
|
173 |
creator = ConversationCreator()
|
174 |
creator.create()
|
175 |
|
176 |
+
conversation_connector = ConversationConnector(
|
177 |
sec_access_token=creator.response_headers[
|
178 |
"x-sydney-encryptedconversationsignature"
|
179 |
],
|
|
|
181 |
conversation_id=creator.response_content["conversationId"],
|
182 |
)
|
183 |
prompt = "Today's weather of California"
|
184 |
+
logger.info(f"\n[User]: {prompt}\n")
|
185 |
+
logger.info(f"[Bing]:")
|
186 |
loop = asyncio.get_event_loop()
|
187 |
+
loop.run_until_complete(conversation_connector.stream_chat(prompt=prompt))
|
188 |
loop.close()
|
logger/__init_.py
ADDED
File without changes
|
logger/logger.py
ADDED
@@ -0,0 +1,241 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import datetime
|
2 |
+
import functools
|
3 |
+
import inspect
|
4 |
+
import logging
|
5 |
+
import os
|
6 |
+
import shutil
|
7 |
+
import subprocess
|
8 |
+
from termcolor import colored
|
9 |
+
|
10 |
+
|
11 |
+
def add_fillers(text, filler="=", fill_side="both"):
|
12 |
+
terminal_width = shutil.get_terminal_size().columns
|
13 |
+
text = text.strip()
|
14 |
+
text_width = len(text)
|
15 |
+
if text_width >= terminal_width:
|
16 |
+
return text
|
17 |
+
|
18 |
+
if fill_side[0].lower() == "b":
|
19 |
+
leading_fill_str = filler * ((terminal_width - text_width) // 2 - 1) + " "
|
20 |
+
trailing_fill_str = " " + filler * (
|
21 |
+
terminal_width - text_width - len(leading_fill_str) - 1
|
22 |
+
)
|
23 |
+
elif fill_side[0].lower() == "l":
|
24 |
+
leading_fill_str = filler * (terminal_width - text_width - 1) + " "
|
25 |
+
trailing_fill_str = ""
|
26 |
+
elif fill_side[0].lower() == "r":
|
27 |
+
leading_fill_str = ""
|
28 |
+
trailing_fill_str = " " + filler * (terminal_width - text_width - 1)
|
29 |
+
else:
|
30 |
+
raise ValueError("Invalid fill_side")
|
31 |
+
|
32 |
+
filled_str = f"{leading_fill_str}{text}{trailing_fill_str}"
|
33 |
+
return filled_str
|
34 |
+
|
35 |
+
|
36 |
+
class Logger:
|
37 |
+
LOG_METHODS = {
|
38 |
+
"err": ("error", "red"),
|
39 |
+
"warn": ("warning", "light_red"),
|
40 |
+
"note": ("info", "light_magenta"),
|
41 |
+
"mesg": ("info", "light_cyan"),
|
42 |
+
"file": ("info", "light_blue"),
|
43 |
+
"line": ("info", "white"),
|
44 |
+
"success": ("info", "light_green"),
|
45 |
+
"fail": ("info", "light_red"),
|
46 |
+
"back": ("debug", "light_cyan"),
|
47 |
+
}
|
48 |
+
INDENT_METHODS = [
|
49 |
+
"indent",
|
50 |
+
"set_indent",
|
51 |
+
"reset_indent",
|
52 |
+
"store_indent",
|
53 |
+
"restore_indent",
|
54 |
+
"log_indent",
|
55 |
+
]
|
56 |
+
LEVEL_METHODS = [
|
57 |
+
"set_level",
|
58 |
+
"store_level",
|
59 |
+
"restore_level",
|
60 |
+
"quiet",
|
61 |
+
"enter_quiet",
|
62 |
+
"exit_quiet",
|
63 |
+
]
|
64 |
+
LEVEL_NAMES = {
|
65 |
+
"critical": logging.CRITICAL,
|
66 |
+
"error": logging.ERROR,
|
67 |
+
"warning": logging.WARNING,
|
68 |
+
"info": logging.INFO,
|
69 |
+
"debug": logging.DEBUG,
|
70 |
+
}
|
71 |
+
|
72 |
+
def __init__(self, name=None, prefix=False):
|
73 |
+
if not name:
|
74 |
+
frame = inspect.stack()[1]
|
75 |
+
module = inspect.getmodule(frame[0])
|
76 |
+
name = module.__name__
|
77 |
+
|
78 |
+
self.logger = logging.getLogger(name)
|
79 |
+
self.logger.setLevel(logging.INFO)
|
80 |
+
|
81 |
+
if prefix:
|
82 |
+
formatter_prefix = "[%(asctime)s] - [%(name)s] - [%(levelname)s]\n"
|
83 |
+
else:
|
84 |
+
formatter_prefix = ""
|
85 |
+
|
86 |
+
self.formatter = logging.Formatter(formatter_prefix + "%(message)s")
|
87 |
+
|
88 |
+
self.handler = logging.StreamHandler()
|
89 |
+
self.handler.setLevel(logging.INFO)
|
90 |
+
|
91 |
+
self.handler.setFormatter(self.formatter)
|
92 |
+
self.logger.addHandler(self.handler)
|
93 |
+
|
94 |
+
self.log_indent = 0
|
95 |
+
self.log_indents = []
|
96 |
+
|
97 |
+
self.log_level = "info"
|
98 |
+
self.log_levels = []
|
99 |
+
|
100 |
+
self.bind_functions()
|
101 |
+
|
102 |
+
def indent(self, indent=2):
|
103 |
+
self.log_indent += indent
|
104 |
+
|
105 |
+
def set_indent(self, indent=2):
|
106 |
+
self.log_indent = indent
|
107 |
+
|
108 |
+
def reset_indent(self):
|
109 |
+
self.log_indent = 0
|
110 |
+
|
111 |
+
def store_indent(self):
|
112 |
+
self.log_indents.append(self.log_indent)
|
113 |
+
|
114 |
+
def restore_indent(self):
|
115 |
+
self.log_indent = self.log_indents.pop(-1)
|
116 |
+
|
117 |
+
def set_level(self, level):
|
118 |
+
self.log_level = level
|
119 |
+
self.logger.setLevel(self.LEVEL_NAMES[level])
|
120 |
+
|
121 |
+
def store_level(self):
|
122 |
+
self.log_levels.append(self.log_level)
|
123 |
+
|
124 |
+
def restore_level(self):
|
125 |
+
self.log_level = self.log_levels.pop(-1)
|
126 |
+
self.set_level(self.log_level)
|
127 |
+
|
128 |
+
def quiet(self):
|
129 |
+
self.set_level("critical")
|
130 |
+
|
131 |
+
def enter_quiet(self, quiet=False):
|
132 |
+
if quiet:
|
133 |
+
self.store_level()
|
134 |
+
self.quiet()
|
135 |
+
|
136 |
+
def exit_quiet(self, quiet=False):
|
137 |
+
if quiet:
|
138 |
+
self.restore_level()
|
139 |
+
|
140 |
+
def log(self, method, msg, indent=0, fill=False, fill_side="both", *args, **kwargs):
|
141 |
+
if type(msg) == str:
|
142 |
+
msg_str = msg
|
143 |
+
else:
|
144 |
+
msg_str = repr(msg)
|
145 |
+
quotes = ["'", '"']
|
146 |
+
if msg_str[0] in quotes and msg_str[-1] in quotes:
|
147 |
+
msg_str = msg_str[1:-1]
|
148 |
+
msg_lines = msg_str.splitlines()
|
149 |
+
|
150 |
+
self.store_indent()
|
151 |
+
self.indent(indent)
|
152 |
+
indent_str = " " * self.log_indent
|
153 |
+
self.restore_indent()
|
154 |
+
|
155 |
+
level, color = self.LOG_METHODS[method]
|
156 |
+
indented_msg = "\n".join([f"{indent_str}{line}" for line in msg_lines])
|
157 |
+
if fill:
|
158 |
+
indented_msg = add_fillers(indented_msg, fill_side=fill_side)
|
159 |
+
getattr(self.logger, level)(colored(indented_msg, color), *args, **kwargs)
|
160 |
+
|
161 |
+
def bind_functions(self):
|
162 |
+
for method in self.LOG_METHODS:
|
163 |
+
setattr(self.logger, method, functools.partial(self.log, method))
|
164 |
+
|
165 |
+
for method in self.INDENT_METHODS:
|
166 |
+
setattr(self.logger, method, getattr(self, method))
|
167 |
+
|
168 |
+
for method in self.LEVEL_METHODS:
|
169 |
+
setattr(self.logger, method, getattr(self, method))
|
170 |
+
|
171 |
+
|
172 |
+
logger = Logger().logger
|
173 |
+
|
174 |
+
|
175 |
+
def shell_cmd(cmd, getoutput=False, showcmd=True, env=None):
|
176 |
+
if showcmd:
|
177 |
+
logger.info(colored(f"\n$ [{os.getcwd()}]", "light_blue"))
|
178 |
+
logger.info(colored(f" $ {cmd}\n", "light_cyan"))
|
179 |
+
if getoutput:
|
180 |
+
output = subprocess.getoutput(cmd, env=env)
|
181 |
+
return output
|
182 |
+
else:
|
183 |
+
subprocess.run(cmd, shell=True, env=env)
|
184 |
+
|
185 |
+
|
186 |
+
class Runtimer:
|
187 |
+
def __enter__(self):
|
188 |
+
self.t1, _ = self.start_time()
|
189 |
+
return self
|
190 |
+
|
191 |
+
def __exit__(self, exc_type, exc_value, traceback):
|
192 |
+
self.t2, _ = self.end_time()
|
193 |
+
self.elapsed_time(self.t2 - self.t1)
|
194 |
+
|
195 |
+
def start_time(self):
|
196 |
+
t1 = datetime.datetime.now()
|
197 |
+
self.logger_time("start", t1)
|
198 |
+
return t1, self.time2str(t1)
|
199 |
+
|
200 |
+
def end_time(self):
|
201 |
+
t2 = datetime.datetime.now()
|
202 |
+
self.logger_time("end", t2)
|
203 |
+
return t2, self.time2str(t2)
|
204 |
+
|
205 |
+
def elapsed_time(self, dt=None):
|
206 |
+
if dt is None:
|
207 |
+
dt = self.t2 - self.t1
|
208 |
+
self.logger_time("elapsed", dt)
|
209 |
+
return dt, self.time2str(dt)
|
210 |
+
|
211 |
+
def logger_time(self, time_type, t):
|
212 |
+
time_types = {
|
213 |
+
"start": "Start",
|
214 |
+
"end": "End",
|
215 |
+
"elapsed": "Elapsed",
|
216 |
+
}
|
217 |
+
time_str = add_fillers(
|
218 |
+
colored(
|
219 |
+
f"{time_types[time_type]} time: [ {self.time2str(t)} ]",
|
220 |
+
"light_magenta",
|
221 |
+
),
|
222 |
+
fill_side="both",
|
223 |
+
)
|
224 |
+
logger.line(time_str)
|
225 |
+
|
226 |
+
# Convert time to string
|
227 |
+
def time2str(self, t):
|
228 |
+
datetime_str_format = "%Y-%m-%d %H:%M:%S"
|
229 |
+
if isinstance(t, datetime.datetime):
|
230 |
+
return t.strftime(datetime_str_format)
|
231 |
+
elif isinstance(t, datetime.timedelta):
|
232 |
+
hours = t.seconds // 3600
|
233 |
+
hour_str = f"{hours} hr" if hours > 0 else ""
|
234 |
+
minutes = (t.seconds // 60) % 60
|
235 |
+
minute_str = f"{minutes:>2} min" if minutes > 0 else ""
|
236 |
+
seconds = t.seconds % 60
|
237 |
+
second_str = f"{seconds:>2} s"
|
238 |
+
time_str = " ".join([hour_str, minute_str, second_str]).strip()
|
239 |
+
return time_str
|
240 |
+
else:
|
241 |
+
return str(t)
|