diff --git a/.gitattributes b/.gitattributes index 13e47cf612aadc5491fa18e14d7e303ae367ae39..9130252b463a218f1dd2aa9bdbec05b97245adfd 100644 --- a/.gitattributes +++ b/.gitattributes @@ -189,3 +189,5 @@ wemm/lib/python3.10/site-packages/triton/third_party/cuda/lib/libdevice.10.bc fi wemm/lib/python3.10/site-packages/pillow.libs/libbrotlicommon-5b2eba61.so.1.1.0 filter=lfs diff=lfs merge=lfs -text wemm/lib/python3.10/site-packages/transformers/models/deta/__pycache__/modeling_deta.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text wemm/lib/python3.10/site-packages/virtualenv/seed/wheels/embed/setuptools-75.3.0-py3-none-any.whl filter=lfs diff=lfs merge=lfs -text +wemm/lib/python3.10/site-packages/safetensors/_safetensors_rust.abi3.so filter=lfs diff=lfs merge=lfs -text +wemm/lib/python3.10/site-packages/transformers/models/speecht5/__pycache__/modeling_speecht5.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text diff --git a/wemm/lib/python3.10/site-packages/lit/BooleanExpression.py b/wemm/lib/python3.10/site-packages/lit/BooleanExpression.py new file mode 100644 index 0000000000000000000000000000000000000000..9b9573d2f3f146ea3762ffe410a80a3d7edb875a --- /dev/null +++ b/wemm/lib/python3.10/site-packages/lit/BooleanExpression.py @@ -0,0 +1,350 @@ +import re + + +class BooleanExpression: + # A simple evaluator of boolean expressions. + # + # Grammar: + # expr :: or_expr + # or_expr :: and_expr ('||' and_expr)* + # and_expr :: not_expr ('&&' not_expr)* + # not_expr :: '!' not_expr + # '(' or_expr ')' + # match_expr + # match_expr :: braced_regex + # identifier + # braced_regex match_expr + # identifier match_expr + # identifier :: [-+=._a-zA-Z0-9]+ + # braced_regex :: '{{' python_regex '}}' + + # Evaluates `string` as a boolean expression. + # Returns True or False. Throws a ValueError on syntax error. + # + # Variables in `variables` are true. + # Regexes that match any variable in `variables` are true. + # 'true' is true. + # All other identifiers are false. + @staticmethod + def evaluate(string, variables): + try: + parser = BooleanExpression(string, set(variables)) + return parser.parseAll() + except ValueError as e: + raise ValueError(str(e) + ("\nin expression: %r" % string)) + + ##### + + def __init__(self, string, variables): + self.tokens = BooleanExpression.tokenize(string) + self.variables = variables + self.variables.add("true") + self.value = None + self.token = None + + # Singleton end-of-expression marker. + END = object() + + # Tokenization pattern. + Pattern = re.compile( + r"\A\s*([()]|&&|\|\||!|(?:[-+=._a-zA-Z0-9]+|\{\{.+?\}\})+)\s*(.*)\Z" + ) + + @staticmethod + def tokenize(string): + while True: + m = re.match(BooleanExpression.Pattern, string) + if m is None: + if string == "": + yield BooleanExpression.END + return + else: + raise ValueError("couldn't parse text: %r" % string) + + token = m.group(1) + string = m.group(2) + yield token + + def quote(self, token): + if token is BooleanExpression.END: + return "" + else: + return repr(token) + + def accept(self, t): + if self.token == t: + self.token = next(self.tokens) + return True + else: + return False + + def expect(self, t): + if self.token == t: + if self.token != BooleanExpression.END: + self.token = next(self.tokens) + else: + raise ValueError( + "expected: %s\nhave: %s" % (self.quote(t), self.quote(self.token)) + ) + + @staticmethod + def isMatchExpression(token): + if ( + token is BooleanExpression.END + or token == "&&" + or token == "||" + or token == "!" + or token == "(" + or token == ")" + ): + return False + return True + + def parseMATCH(self): + regex = "" + for part in filter(None, re.split(r"(\{\{.+?\}\})", self.token)): + if part.startswith("{{"): + assert part.endswith("}}") + regex += "(?:{})".format(part[2:-2]) + else: + regex += re.escape(part) + regex = re.compile(regex) + self.value = any(regex.fullmatch(var) for var in self.variables) + self.token = next(self.tokens) + + def parseNOT(self): + if self.accept("!"): + self.parseNOT() + self.value = not self.value + elif self.accept("("): + self.parseOR() + self.expect(")") + elif not BooleanExpression.isMatchExpression(self.token): + raise ValueError( + "expected: '!', '(', '{{', or identifier\nhave: %s" + % self.quote(self.token) + ) + else: + self.parseMATCH() + + def parseAND(self): + self.parseNOT() + while self.accept("&&"): + left = self.value + self.parseNOT() + right = self.value + # this is technically the wrong associativity, but it + # doesn't matter for this limited expression grammar + self.value = left and right + + def parseOR(self): + self.parseAND() + while self.accept("||"): + left = self.value + self.parseAND() + right = self.value + # this is technically the wrong associativity, but it + # doesn't matter for this limited expression grammar + self.value = left or right + + def parseAll(self): + self.token = next(self.tokens) + self.parseOR() + self.expect(BooleanExpression.END) + return self.value + + +####### +# Tests + +import unittest + + +class TestBooleanExpression(unittest.TestCase): + def test_variables(self): + variables = {"its-true", "false-lol-true", "under_score", "e=quals", "d1g1ts"} + self.assertTrue(BooleanExpression.evaluate("true", variables)) + self.assertTrue(BooleanExpression.evaluate("its-true", variables)) + self.assertTrue(BooleanExpression.evaluate("false-lol-true", variables)) + self.assertTrue(BooleanExpression.evaluate("under_score", variables)) + self.assertTrue(BooleanExpression.evaluate("e=quals", variables)) + self.assertTrue(BooleanExpression.evaluate("d1g1ts", variables)) + self.assertTrue(BooleanExpression.evaluate("{{its.+}}", variables)) + self.assertTrue(BooleanExpression.evaluate("{{false-[lo]+-true}}", variables)) + self.assertTrue( + BooleanExpression.evaluate("{{(true|false)-lol-(true|false)}}", variables) + ) + self.assertTrue(BooleanExpression.evaluate("d1g{{[0-9]}}ts", variables)) + self.assertTrue(BooleanExpression.evaluate("d1g{{[0-9]}}t{{[a-z]}}", variables)) + self.assertTrue( + BooleanExpression.evaluate("{{d}}1g{{[0-9]}}t{{[a-z]}}", variables) + ) + self.assertTrue(BooleanExpression.evaluate("d1{{(g|1)+}}ts", variables)) + + self.assertFalse(BooleanExpression.evaluate("false", variables)) + self.assertFalse(BooleanExpression.evaluate("True", variables)) + self.assertFalse(BooleanExpression.evaluate("true-ish", variables)) + self.assertFalse(BooleanExpression.evaluate("not_true", variables)) + self.assertFalse(BooleanExpression.evaluate("tru", variables)) + self.assertFalse(BooleanExpression.evaluate("{{its-true.+}}", variables)) + + def test_matching(self): + expr1 = "linux && (target={{aarch64-.+}} || target={{x86_64-.+}})" + self.assertTrue( + BooleanExpression.evaluate( + expr1, {"linux", "target=x86_64-unknown-linux-gnu"} + ) + ) + self.assertFalse( + BooleanExpression.evaluate( + expr1, {"linux", "target=i386-unknown-linux-gnu"} + ) + ) + + expr2 = "use_system_cxx_lib && target={{.+}}-apple-macosx10.{{9|10|11|12}} && !no-exceptions" + self.assertTrue( + BooleanExpression.evaluate( + expr2, {"use_system_cxx_lib", "target=arm64-apple-macosx10.12"} + ) + ) + self.assertFalse( + BooleanExpression.evaluate( + expr2, + { + "use_system_cxx_lib", + "target=arm64-apple-macosx10.12", + "no-exceptions", + }, + ) + ) + self.assertFalse( + BooleanExpression.evaluate( + expr2, {"use_system_cxx_lib", "target=arm64-apple-macosx10.15"} + ) + ) + + def test_operators(self): + self.assertTrue(BooleanExpression.evaluate("true || true", {})) + self.assertTrue(BooleanExpression.evaluate("true || false", {})) + self.assertTrue(BooleanExpression.evaluate("false || true", {})) + self.assertFalse(BooleanExpression.evaluate("false || false", {})) + + self.assertTrue(BooleanExpression.evaluate("true && true", {})) + self.assertFalse(BooleanExpression.evaluate("true && false", {})) + self.assertFalse(BooleanExpression.evaluate("false && true", {})) + self.assertFalse(BooleanExpression.evaluate("false && false", {})) + + self.assertFalse(BooleanExpression.evaluate("!true", {})) + self.assertTrue(BooleanExpression.evaluate("!false", {})) + + self.assertTrue(BooleanExpression.evaluate(" ((!((false) )) ) ", {})) + self.assertTrue(BooleanExpression.evaluate("true && (true && (true))", {})) + self.assertTrue(BooleanExpression.evaluate("!false && !false && !! !false", {})) + self.assertTrue(BooleanExpression.evaluate("false && false || true", {})) + self.assertTrue(BooleanExpression.evaluate("(false && false) || true", {})) + self.assertFalse(BooleanExpression.evaluate("false && (false || true)", {})) + + # Evaluate boolean expression `expr`. + # Fail if it does not throw a ValueError containing the text `error`. + def checkException(self, expr, error): + try: + BooleanExpression.evaluate(expr, {}) + self.fail("expression %r didn't cause an exception" % expr) + except ValueError as e: + if -1 == str(e).find(error): + self.fail( + ( + "expression %r caused the wrong ValueError\n" + + "actual error was:\n%s\n" + + "expected error was:\n%s\n" + ) + % (expr, e, error) + ) + except BaseException as e: + self.fail( + ( + "expression %r caused the wrong exception; actual " + + "exception was: \n%r" + ) + % (expr, e) + ) + + def test_errors(self): + self.checkException( + "ba#d", "couldn't parse text: '#d'\n" + "in expression: 'ba#d'" + ) + + self.checkException( + "true and true", + "expected: \n" + + "have: 'and'\n" + + "in expression: 'true and true'", + ) + + self.checkException( + "|| true", + "expected: '!', '(', '{{', or identifier\n" + + "have: '||'\n" + + "in expression: '|| true'", + ) + + self.checkException( + "true &&", + "expected: '!', '(', '{{', or identifier\n" + + "have: \n" + + "in expression: 'true &&'", + ) + + self.checkException( + "", + "expected: '!', '(', '{{', or identifier\n" + + "have: \n" + + "in expression: ''", + ) + + self.checkException("*", "couldn't parse text: '*'\n" + "in expression: '*'") + + self.checkException( + "no wait stop", + "expected: \n" + + "have: 'wait'\n" + + "in expression: 'no wait stop'", + ) + + self.checkException( + "no-$-please", + "couldn't parse text: '$-please'\n" + "in expression: 'no-$-please'", + ) + + self.checkException( + "(((true && true) || true)", + "expected: ')'\n" + + "have: \n" + + "in expression: '(((true && true) || true)'", + ) + + self.checkException( + "true (true)", + "expected: \n" + + "have: '('\n" + + "in expression: 'true (true)'", + ) + + self.checkException( + "( )", + "expected: '!', '(', '{{', or identifier\n" + + "have: ')'\n" + + "in expression: '( )'", + ) + + self.checkException( + "abc{{def", "couldn't parse text: '{{def'\n" + "in expression: 'abc{{def'" + ) + + self.checkException( + "{{}}", "couldn't parse text: '{{}}'\n" + "in expression: '{{}}'" + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/wemm/lib/python3.10/site-packages/lit/LitTestCase.py b/wemm/lib/python3.10/site-packages/lit/LitTestCase.py new file mode 100644 index 0000000000000000000000000000000000000000..566d068ad11eaf7de9a1a8777b0e637cfe08ece9 --- /dev/null +++ b/wemm/lib/python3.10/site-packages/lit/LitTestCase.py @@ -0,0 +1,65 @@ +import unittest + +import lit.discovery +import lit.LitConfig +import lit.worker + +""" +TestCase adaptor for providing a Python 'unittest' compatible interface to 'lit' +tests. +""" + + +class UnresolvedError(RuntimeError): + pass + + +class LitTestCase(unittest.TestCase): + def __init__(self, test, lit_config): + unittest.TestCase.__init__(self) + self._test = test + self._lit_config = lit_config + + def id(self): + return self._test.getFullName() + + def shortDescription(self): + return self._test.getFullName() + + def runTest(self): + # Run the test. + result = lit.worker._execute(self._test, self._lit_config) + + # Adapt the result to unittest. + if result.code is lit.Test.UNRESOLVED: + raise UnresolvedError(result.output) + elif result.code.isFailure: + self.fail(result.output) + + +def load_test_suite(inputs): + import platform + + windows = platform.system() == "Windows" + + # Create the global config object. + lit_config = lit.LitConfig.LitConfig( + progname="lit", + path=[], + quiet=False, + useValgrind=False, + valgrindLeakCheck=False, + valgrindArgs=[], + noExecute=False, + debug=False, + isWindows=windows, + order="smart", + params={}, + ) + + # Perform test discovery. + tests = lit.discovery.find_tests_for_inputs(lit_config, inputs) + test_adaptors = [LitTestCase(t, lit_config) for t in tests] + + # Return a unittest test suite which just runs the tests in order. + return unittest.TestSuite(test_adaptors) diff --git a/wemm/lib/python3.10/site-packages/lit/ProgressBar.py b/wemm/lib/python3.10/site-packages/lit/ProgressBar.py new file mode 100644 index 0000000000000000000000000000000000000000..382b8f2e52540cc48797ebe70920cc92df089c2e --- /dev/null +++ b/wemm/lib/python3.10/site-packages/lit/ProgressBar.py @@ -0,0 +1,326 @@ +#!/usr/bin/env python + +# Source: http://code.activestate.com/recipes/475116/, with +# modifications by Daniel Dunbar. + +import sys, re, time + + +def to_bytes(str): + # Encode to UTF-8 to get binary data. + return str.encode("utf-8") + + +class TerminalController: + """ + A class that can be used to portably generate formatted output to + a terminal. + + `TerminalController` defines a set of instance variables whose + values are initialized to the control sequence necessary to + perform a given action. These can be simply included in normal + output to the terminal: + + >>> term = TerminalController() + >>> print('This is '+term.GREEN+'green'+term.NORMAL) + + Alternatively, the `render()` method can used, which replaces + '${action}' with the string required to perform 'action': + + >>> term = TerminalController() + >>> print(term.render('This is ${GREEN}green${NORMAL}')) + + If the terminal doesn't support a given action, then the value of + the corresponding instance variable will be set to ''. As a + result, the above code will still work on terminals that do not + support color, except that their output will not be colored. + Also, this means that you can test whether the terminal supports a + given action by simply testing the truth value of the + corresponding instance variable: + + >>> term = TerminalController() + >>> if term.CLEAR_SCREEN: + ... print('This terminal supports clearning the screen.') + + Finally, if the width and height of the terminal are known, then + they will be stored in the `COLS` and `LINES` attributes. + """ + + # Cursor movement: + BOL = "" #: Move the cursor to the beginning of the line + UP = "" #: Move the cursor up one line + DOWN = "" #: Move the cursor down one line + LEFT = "" #: Move the cursor left one char + RIGHT = "" #: Move the cursor right one char + + # Deletion: + CLEAR_SCREEN = "" #: Clear the screen and move to home position + CLEAR_EOL = "" #: Clear to the end of the line. + CLEAR_BOL = "" #: Clear to the beginning of the line. + CLEAR_EOS = "" #: Clear to the end of the screen + + # Output modes: + BOLD = "" #: Turn on bold mode + BLINK = "" #: Turn on blink mode + DIM = "" #: Turn on half-bright mode + REVERSE = "" #: Turn on reverse-video mode + NORMAL = "" #: Turn off all modes + + # Cursor display: + HIDE_CURSOR = "" #: Make the cursor invisible + SHOW_CURSOR = "" #: Make the cursor visible + + # Terminal size: + COLS = None #: Width of the terminal (None for unknown) + LINES = None #: Height of the terminal (None for unknown) + + # Foreground colors: + BLACK = BLUE = GREEN = CYAN = RED = MAGENTA = YELLOW = WHITE = "" + + # Background colors: + BG_BLACK = BG_BLUE = BG_GREEN = BG_CYAN = "" + BG_RED = BG_MAGENTA = BG_YELLOW = BG_WHITE = "" + + _STRING_CAPABILITIES = """ + BOL=cr UP=cuu1 DOWN=cud1 LEFT=cub1 RIGHT=cuf1 + CLEAR_SCREEN=clear CLEAR_EOL=el CLEAR_BOL=el1 CLEAR_EOS=ed BOLD=bold + BLINK=blink DIM=dim REVERSE=rev UNDERLINE=smul NORMAL=sgr0 + HIDE_CURSOR=cinvis SHOW_CURSOR=cnorm""".split() + _COLORS = """BLACK BLUE GREEN CYAN RED MAGENTA YELLOW WHITE""".split() + _ANSICOLORS = "BLACK RED GREEN YELLOW BLUE MAGENTA CYAN WHITE".split() + + def __init__(self, term_stream=sys.stdout): + """ + Create a `TerminalController` and initialize its attributes + with appropriate values for the current terminal. + `term_stream` is the stream that will be used for terminal + output; if this stream is not a tty, then the terminal is + assumed to be a dumb terminal (i.e., have no capabilities). + """ + # Curses isn't available on all platforms + try: + import curses + except: + return + + # If the stream isn't a tty, then assume it has no capabilities. + if not term_stream.isatty(): + return + + # Check the terminal type. If we fail, then assume that the + # terminal has no capabilities. + try: + curses.setupterm() + except: + return + + # Look up numeric capabilities. + self.COLS = curses.tigetnum("cols") + self.LINES = curses.tigetnum("lines") + self.XN = curses.tigetflag("xenl") + + # Look up string capabilities. + for capability in self._STRING_CAPABILITIES: + (attrib, cap_name) = capability.split("=") + setattr(self, attrib, self._tigetstr(cap_name) or "") + + # Colors + set_fg = self._tigetstr("setf") + if set_fg: + for i, color in zip(range(len(self._COLORS)), self._COLORS): + setattr(self, color, self._tparm(set_fg, i)) + set_fg_ansi = self._tigetstr("setaf") + if set_fg_ansi: + for i, color in zip(range(len(self._ANSICOLORS)), self._ANSICOLORS): + setattr(self, color, self._tparm(set_fg_ansi, i)) + set_bg = self._tigetstr("setb") + if set_bg: + for i, color in zip(range(len(self._COLORS)), self._COLORS): + setattr(self, "BG_" + color, self._tparm(set_bg, i)) + set_bg_ansi = self._tigetstr("setab") + if set_bg_ansi: + for i, color in zip(range(len(self._ANSICOLORS)), self._ANSICOLORS): + setattr(self, "BG_" + color, self._tparm(set_bg_ansi, i)) + + def _tparm(self, arg, index): + import curses + + return curses.tparm(to_bytes(arg), index).decode("utf-8") or "" + + def _tigetstr(self, cap_name): + # String capabilities can include "delays" of the form "$<2>". + # For any modern terminal, we should be able to just ignore + # these, so strip them out. + import curses + + cap = curses.tigetstr(cap_name) + if cap is None: + cap = "" + else: + cap = cap.decode("utf-8") + return re.sub(r"\$<\d+>[/*]?", "", cap) + + def render(self, template): + """ + Replace each $-substitutions in the given template string with + the corresponding terminal control string (if it's defined) or + '' (if it's not). + """ + return re.sub(r"\$\$|\${\w+}", self._render_sub, template) + + def _render_sub(self, match): + s = match.group() + if s == "$$": + return s + else: + return getattr(self, s[2:-1]) + + +####################################################################### +# Example use case: progress bar +####################################################################### + + +class SimpleProgressBar: + """ + A simple progress bar which doesn't need any terminal support. + + This prints out a progress bar like: + 'Header: 0.. 10.. 20.. ...' + """ + + def __init__(self, header): + self.header = header + self.atIndex = None + + def update(self, percent, message): + if self.atIndex is None: + sys.stdout.write(self.header) + self.atIndex = 0 + + next = int(percent * 50) + if next == self.atIndex: + return + + for i in range(self.atIndex, next): + idx = i % 5 + if idx == 0: + sys.stdout.write("%2d" % (i * 2)) + elif idx == 1: + pass # Skip second char + elif idx < 4: + sys.stdout.write(".") + else: + sys.stdout.write(" ") + sys.stdout.flush() + self.atIndex = next + + def clear(self, interrupted): + if self.atIndex is not None and not interrupted: + sys.stdout.write("\n") + sys.stdout.flush() + self.atIndex = None + + +class ProgressBar: + """ + A 3-line progress bar, which looks like:: + + Header + 20% [===========----------------------------------] + progress message + + The progress bar is colored, if the terminal supports color + output; and adjusts to the width of the terminal. + """ + + BAR = "%s${%s}[${BOLD}%s%s${NORMAL}${%s}]${NORMAL}%s" + HEADER = "${BOLD}${CYAN}%s${NORMAL}\n\n" + + def __init__(self, term, header, useETA=True): + self.term = term + if not (self.term.CLEAR_EOL and self.term.UP and self.term.BOL): + raise ValueError( + "Terminal isn't capable enough -- you " + "should use a simpler progress dispaly." + ) + self.BOL = self.term.BOL # BoL from col#79 + self.XNL = "\n" # Newline from col#79 + if self.term.COLS: + self.width = self.term.COLS + if not self.term.XN: + self.BOL = self.term.UP + self.term.BOL + self.XNL = "" # Cursor must be fed to the next line + else: + self.width = 75 + self.barColor = "GREEN" + self.header = self.term.render(self.HEADER % header.center(self.width)) + self.cleared = 1 #: true if we haven't drawn the bar yet. + self.useETA = useETA + if self.useETA: + self.startTime = time.time() + # self.update(0, '') + + def update(self, percent, message): + if self.cleared: + sys.stdout.write(self.header) + self.cleared = 0 + prefix = "%3d%% " % (percent * 100,) + suffix = "" + if self.useETA: + elapsed = time.time() - self.startTime + if percent > 0.0001 and elapsed > 1: + total = elapsed / percent + eta = total - elapsed + h = eta // 3600.0 + m = (eta // 60) % 60 + s = eta % 60 + suffix = " ETA: %02d:%02d:%02d" % (h, m, s) + barWidth = self.width - len(prefix) - len(suffix) - 2 + n = int(barWidth * percent) + if len(message) < self.width: + message = message + " " * (self.width - len(message)) + else: + message = "... " + message[-(self.width - 4) :] + bc = self.barColor + bar = self.BAR % (prefix, bc, "=" * n, "-" * (barWidth - n), bc, suffix) + bar = self.term.render(bar) + sys.stdout.write( + self.BOL + + self.term.UP + + self.term.CLEAR_EOL + + bar + + self.XNL + + self.term.CLEAR_EOL + + message + ) + if not self.term.XN: + sys.stdout.flush() + + def clear(self, interrupted): + if not self.cleared: + sys.stdout.write( + self.BOL + + self.term.CLEAR_EOL + + self.term.UP + + self.term.CLEAR_EOL + + self.term.UP + + self.term.CLEAR_EOL + ) + if interrupted: # ^C creates extra line. Gobble it up! + sys.stdout.write(self.term.UP + self.term.CLEAR_EOL) + sys.stdout.write("^C") + sys.stdout.flush() + self.cleared = 1 + + +def test(): + tc = TerminalController() + p = ProgressBar(tc, "Tests") + for i in range(101): + p.update(i / 100.0, str(i)) + time.sleep(0.3) + + +if __name__ == "__main__": + test() diff --git a/wemm/lib/python3.10/site-packages/lit/ShCommands.py b/wemm/lib/python3.10/site-packages/lit/ShCommands.py new file mode 100644 index 0000000000000000000000000000000000000000..68655a41d7934b7de7a961f2e3be5b41b93d2a8f --- /dev/null +++ b/wemm/lib/python3.10/site-packages/lit/ShCommands.py @@ -0,0 +1,113 @@ +class Command: + def __init__(self, args, redirects): + self.args = list(args) + self.redirects = list(redirects) + + def __repr__(self): + return "Command(%r, %r)" % (self.args, self.redirects) + + def __eq__(self, other): + if not isinstance(other, Command): + return False + + return (self.args, self.redirects) == (other.args, other.redirects) + + def toShell(self, file): + for arg in self.args: + if "'" not in arg: + quoted = "'%s'" % arg + elif '"' not in arg and "$" not in arg: + quoted = '"%s"' % arg + else: + raise NotImplementedError("Unable to quote %r" % arg) + file.write(quoted) + + # For debugging / validation. + import ShUtil + + dequoted = list(ShUtil.ShLexer(quoted).lex()) + if dequoted != [arg]: + raise NotImplementedError("Unable to quote %r" % arg) + + for r in self.redirects: + if len(r[0]) == 1: + file.write("%s '%s'" % (r[0][0], r[1])) + else: + file.write("%s%s '%s'" % (r[0][1], r[0][0], r[1])) + + +class GlobItem: + def __init__(self, pattern): + self.pattern = pattern + + def __repr__(self): + return self.pattern + + def __eq__(self, other): + if not isinstance(other, Command): + return False + + return self.pattern == other.pattern + + def resolve(self, cwd): + import glob + import os + + if os.path.isabs(self.pattern): + abspath = self.pattern + else: + abspath = os.path.join(cwd, self.pattern) + results = glob.glob(abspath) + return [self.pattern] if len(results) == 0 else results + + +class Pipeline: + def __init__(self, commands, negate=False, pipe_err=False): + self.commands = commands + self.negate = negate + self.pipe_err = pipe_err + + def __repr__(self): + return "Pipeline(%r, %r, %r)" % (self.commands, self.negate, self.pipe_err) + + def __eq__(self, other): + if not isinstance(other, Pipeline): + return False + + return (self.commands, self.negate, self.pipe_err) == ( + other.commands, + other.negate, + self.pipe_err, + ) + + def toShell(self, file, pipefail=False): + if pipefail != self.pipe_err: + raise ValueError('Inconsistent "pipefail" attribute!') + if self.negate: + file.write("! ") + for cmd in self.commands: + cmd.toShell(file) + if cmd is not self.commands[-1]: + file.write("|\n ") + + +class Seq: + def __init__(self, lhs, op, rhs): + assert op in (";", "&", "||", "&&") + self.op = op + self.lhs = lhs + self.rhs = rhs + + def __repr__(self): + return "Seq(%r, %r, %r)" % (self.lhs, self.op, self.rhs) + + def __eq__(self, other): + if not isinstance(other, Seq): + return False + + return (self.lhs, self.op, self.rhs) == (other.lhs, other.op, other.rhs) + + def toShell(self, file, pipefail=False): + self.lhs.toShell(file, pipefail) + file.write(" %s\n" % self.op) + self.rhs.toShell(file, pipefail) diff --git a/wemm/lib/python3.10/site-packages/lit/ShUtil.py b/wemm/lib/python3.10/site-packages/lit/ShUtil.py new file mode 100644 index 0000000000000000000000000000000000000000..fa13167cad1be5b14dd84a046fdbd3fa08f337ed --- /dev/null +++ b/wemm/lib/python3.10/site-packages/lit/ShUtil.py @@ -0,0 +1,272 @@ +from __future__ import absolute_import +import itertools + +import lit.util +from lit.ShCommands import Command, GlobItem, Pipeline, Seq + + +class ShLexer: + def __init__(self, data, win32Escapes=False): + self.data = data + self.pos = 0 + self.end = len(data) + self.win32Escapes = win32Escapes + + def eat(self): + c = self.data[self.pos] + self.pos += 1 + return c + + def look(self): + return self.data[self.pos] + + def maybe_eat(self, c): + """ + maybe_eat(c) - Consume the character c if it is the next character, + returning True if a character was consumed.""" + if self.data[self.pos] == c: + self.pos += 1 + return True + return False + + def lex_arg_fast(self, c): + # Get the leading whitespace free section. + chunk = self.data[self.pos - 1 :].split(None, 1)[0] + + # If it has special characters, the fast path failed. + if ( + "|" in chunk + or "&" in chunk + or "<" in chunk + or ">" in chunk + or "'" in chunk + or '"' in chunk + or ";" in chunk + or "\\" in chunk + ): + return None + + self.pos = self.pos - 1 + len(chunk) + return GlobItem(chunk) if "*" in chunk or "?" in chunk else chunk + + def lex_arg_slow(self, c): + if c in "'\"": + str = self.lex_arg_quoted(c) + else: + str = c + unquoted_glob_char = False + quoted_glob_char = False + while self.pos != self.end: + c = self.look() + if c.isspace() or c in "|&;": + break + elif c in "><": + # This is an annoying case; we treat '2>' as a single token so + # we don't have to track whitespace tokens. + + # If the parse string isn't an integer, do the usual thing. + if not str.isdigit(): + break + + # Otherwise, lex the operator and convert to a redirection + # token. + num = int(str) + tok = self.lex_one_token() + assert isinstance(tok, tuple) and len(tok) == 1 + return (tok[0], num) + elif c == '"' or c == "'": + self.eat() + quoted_arg = self.lex_arg_quoted(c) + if "*" in quoted_arg or "?" in quoted_arg: + quoted_glob_char = True + str += quoted_arg + elif not self.win32Escapes and c == "\\": + # Outside of a string, '\\' escapes everything. + self.eat() + if self.pos == self.end: + lit.util.warning( + "escape at end of quoted argument in: %r" % self.data + ) + return str + str += self.eat() + elif c in "*?": + unquoted_glob_char = True + str += self.eat() + else: + str += self.eat() + # If a quote character is present, lex_arg_quoted will remove the quotes + # and append the argument directly. This causes a problem when the + # quoted portion contains a glob character, as the character will no + # longer be treated literally. If glob characters occur *only* inside + # of quotes, then we can handle this by not globbing at all, and if + # glob characters occur *only* outside of quotes, we can still glob just + # fine. But if a glob character occurs both inside and outside of + # quotes this presents a problem. In practice this is such an obscure + # edge case that it doesn't seem worth the added complexity to support. + # By adding an assertion, it means some bot somewhere will catch this + # and flag the user of a non-portable test (which could almost certainly + # be re-written to work correctly without triggering this). + assert not (quoted_glob_char and unquoted_glob_char) + return GlobItem(str) if unquoted_glob_char else str + + def lex_arg_quoted(self, delim): + str = "" + while self.pos != self.end: + c = self.eat() + if c == delim: + return str + elif c == "\\" and delim == '"': + # Inside a '"' quoted string, '\\' only escapes the quote + # character and backslash, otherwise it is preserved. + if self.pos == self.end: + lit.util.warning( + "escape at end of quoted argument in: %r" % self.data + ) + return str + c = self.eat() + if c == '"': # + str += '"' + elif c == "\\": + str += "\\" + else: + str += "\\" + c + else: + str += c + lit.util.warning("missing quote character in %r" % self.data) + return str + + def lex_arg_checked(self, c): + pos = self.pos + res = self.lex_arg_fast(c) + end = self.pos + + self.pos = pos + reference = self.lex_arg_slow(c) + if res is not None: + if res != reference: + raise ValueError("Fast path failure: %r != %r" % (res, reference)) + if self.pos != end: + raise ValueError("Fast path failure: %r != %r" % (self.pos, end)) + return reference + + def lex_arg(self, c): + return self.lex_arg_fast(c) or self.lex_arg_slow(c) + + def lex_one_token(self): + """ + lex_one_token - Lex a single 'sh' token.""" + + c = self.eat() + if c == ";": + return (c,) + if c == "|": + if self.maybe_eat("|"): + return ("||",) + return (c,) + if c == "&": + if self.maybe_eat("&"): + return ("&&",) + if self.maybe_eat(">"): + return ("&>",) + return (c,) + if c == ">": + if self.maybe_eat("&"): + return (">&",) + if self.maybe_eat(">"): + return (">>",) + return (c,) + if c == "<": + if self.maybe_eat("&"): + return ("<&",) + if self.maybe_eat(">"): + return ("<<",) + return (c,) + + return self.lex_arg(c) + + def lex(self): + while self.pos != self.end: + if self.look().isspace(): + self.eat() + else: + yield self.lex_one_token() + + +### + + +class ShParser: + def __init__(self, data, win32Escapes=False, pipefail=False): + self.data = data + self.pipefail = pipefail + self.tokens = ShLexer(data, win32Escapes=win32Escapes).lex() + + def lex(self): + for item in self.tokens: + return item + return None + + def look(self): + token = self.lex() + if token is not None: + self.tokens = itertools.chain([token], self.tokens) + return token + + def parse_command(self): + tok = self.lex() + if not tok: + raise ValueError("empty command!") + if isinstance(tok, tuple): + raise ValueError("syntax error near unexpected token %r" % tok[0]) + + args = [tok] + redirects = [] + while 1: + tok = self.look() + + # EOF? + if tok is None: + break + + # If this is an argument, just add it to the current command. + if isinstance(tok, (str, GlobItem)): + args.append(self.lex()) + continue + + # Otherwise see if it is a terminator. + assert isinstance(tok, tuple) + if tok[0] in ("|", ";", "&", "||", "&&"): + break + + # Otherwise it must be a redirection. + op = self.lex() + arg = self.lex() + if not arg: + raise ValueError("syntax error near token %r" % op[0]) + redirects.append((op, arg)) + + return Command(args, redirects) + + def parse_pipeline(self): + negate = False + + commands = [self.parse_command()] + while self.look() == ("|",): + self.lex() + commands.append(self.parse_command()) + return Pipeline(commands, negate, self.pipefail) + + def parse(self): + lhs = self.parse_pipeline() + + while self.look(): + operator = self.lex() + assert isinstance(operator, tuple) and len(operator) == 1 + + if not self.look(): + raise ValueError("missing argument to operator %r" % operator[0]) + + # FIXME: Operator precedence!! + lhs = Seq(lhs, operator[0], self.parse_pipeline()) + + return lhs diff --git a/wemm/lib/python3.10/site-packages/lit/TestRunner.py b/wemm/lib/python3.10/site-packages/lit/TestRunner.py new file mode 100644 index 0000000000000000000000000000000000000000..da7fa86fd391733edc2333882e819c8b9b50b626 --- /dev/null +++ b/wemm/lib/python3.10/site-packages/lit/TestRunner.py @@ -0,0 +1,2278 @@ +from __future__ import absolute_import +import errno +import io +import itertools +import getopt +import os, signal, subprocess, sys +import re +import stat +import pathlib +import platform +import shlex +import shutil +import tempfile +import threading +import typing +from typing import Optional, Tuple + +import io + +try: + from StringIO import StringIO +except ImportError: + from io import StringIO + +from lit.ShCommands import GlobItem, Command +import lit.ShUtil as ShUtil +import lit.Test as Test +import lit.util +from lit.util import to_bytes, to_string, to_unicode +from lit.BooleanExpression import BooleanExpression + + +class InternalShellError(Exception): + def __init__(self, command, message): + self.command = command + self.message = message + + +class ScriptFatal(Exception): + """ + A script had a fatal error such that there's no point in retrying. The + message has not been emitted on stdout or stderr but is instead included in + this exception. + """ + + def __init__(self, message): + super().__init__(message) + + +kIsWindows = platform.system() == "Windows" + +# Don't use close_fds on Windows. +kUseCloseFDs = not kIsWindows + +# Use temporary files to replace /dev/null on Windows. +kAvoidDevNull = kIsWindows +kDevNull = "/dev/null" + +# A regex that matches %dbg(ARG), which lit inserts at the beginning of each +# run command pipeline such that ARG specifies the pipeline's source line +# number. lit later expands each %dbg(ARG) to a command that behaves as a null +# command in the target shell so that the line number is seen in lit's verbose +# mode. +# +# This regex captures ARG. ARG must not contain a right parenthesis, which +# terminates %dbg. ARG must not contain quotes, in which ARG might be enclosed +# during expansion. +# +# COMMAND that follows %dbg(ARG) is also captured. COMMAND can be +# empty as a result of conditinal substitution. +kPdbgRegex = "%dbg\\(([^)'\"]*)\\)((?:.|\\n)*)" + + +def buildPdbgCommand(msg, cmd): + res = f"%dbg({msg}) {cmd}" + assert re.fullmatch( + kPdbgRegex, res + ), f"kPdbgRegex expected to match actual %dbg usage: {res}" + return res + + +class ShellEnvironment(object): + + """Mutable shell environment containing things like CWD and env vars. + + Environment variables are not implemented, but cwd tracking is. In addition, + we maintain a dir stack for pushd/popd. + """ + + def __init__(self, cwd, env): + self.cwd = cwd + self.env = dict(env) + self.dirStack = [] + + def change_dir(self, newdir): + if os.path.isabs(newdir): + self.cwd = newdir + else: + self.cwd = lit.util.abs_path_preserve_drive(os.path.join(self.cwd, newdir)) + + +class TimeoutHelper(object): + """ + Object used to helper manage enforcing a timeout in + _executeShCmd(). It is passed through recursive calls + to collect processes that have been executed so that when + the timeout happens they can be killed. + """ + + def __init__(self, timeout): + self.timeout = timeout + self._procs = [] + self._timeoutReached = False + self._doneKillPass = False + # This lock will be used to protect concurrent access + # to _procs and _doneKillPass + self._lock = None + self._timer = None + + def cancel(self): + if not self.active(): + return + self._timer.cancel() + + def active(self): + return self.timeout > 0 + + def addProcess(self, proc): + if not self.active(): + return + needToRunKill = False + with self._lock: + self._procs.append(proc) + # Avoid re-entering the lock by finding out if kill needs to be run + # again here but call it if necessary once we have left the lock. + # We could use a reentrant lock here instead but this code seems + # clearer to me. + needToRunKill = self._doneKillPass + + # The initial call to _kill() from the timer thread already happened so + # we need to call it again from this thread, otherwise this process + # will be left to run even though the timeout was already hit + if needToRunKill: + assert self.timeoutReached() + self._kill() + + def startTimer(self): + if not self.active(): + return + + # Do some late initialisation that's only needed + # if there is a timeout set + self._lock = threading.Lock() + self._timer = threading.Timer(self.timeout, self._handleTimeoutReached) + self._timer.start() + + def _handleTimeoutReached(self): + self._timeoutReached = True + self._kill() + + def timeoutReached(self): + return self._timeoutReached + + def _kill(self): + """ + This method may be called multiple times as we might get unlucky + and be in the middle of creating a new process in _executeShCmd() + which won't yet be in ``self._procs``. By locking here and in + addProcess() we should be able to kill processes launched after + the initial call to _kill() + """ + with self._lock: + for p in self._procs: + lit.util.killProcessAndChildren(p.pid) + # Empty the list and note that we've done a pass over the list + self._procs = [] # Python2 doesn't have list.clear() + self._doneKillPass = True + + +class ShellCommandResult(object): + """Captures the result of an individual command.""" + + def __init__( + self, command, stdout, stderr, exitCode, timeoutReached, outputFiles=[] + ): + self.command = command + self.stdout = stdout + self.stderr = stderr + self.exitCode = exitCode + self.timeoutReached = timeoutReached + self.outputFiles = list(outputFiles) + + +def executeShCmd(cmd, shenv, results, timeout=0): + """ + Wrapper around _executeShCmd that handles + timeout + """ + # Use the helper even when no timeout is required to make + # other code simpler (i.e. avoid bunch of ``!= None`` checks) + timeoutHelper = TimeoutHelper(timeout) + if timeout > 0: + timeoutHelper.startTimer() + finalExitCode = _executeShCmd(cmd, shenv, results, timeoutHelper) + timeoutHelper.cancel() + timeoutInfo = None + if timeoutHelper.timeoutReached(): + timeoutInfo = "Reached timeout of {} seconds".format(timeout) + + return (finalExitCode, timeoutInfo) + + +def expand_glob(arg, cwd): + if isinstance(arg, GlobItem): + return sorted(arg.resolve(cwd)) + return [arg] + + +def expand_glob_expressions(args, cwd): + result = [args[0]] + for arg in args[1:]: + result.extend(expand_glob(arg, cwd)) + return result + + +def quote_windows_command(seq): + r""" + Reimplement Python's private subprocess.list2cmdline for MSys compatibility + + Based on CPython implementation here: + https://hg.python.org/cpython/file/849826a900d2/Lib/subprocess.py#l422 + + Some core util distributions (MSys) don't tokenize command line arguments + the same way that MSVC CRT does. Lit rolls its own quoting logic similar to + the stock CPython logic to paper over these quoting and tokenization rule + differences. + + We use the same algorithm from MSDN as CPython + (http://msdn.microsoft.com/en-us/library/17w5ykft.aspx), but we treat more + characters as needing quoting, such as double quotes themselves, and square + brackets. + + For MSys based tools, this is very brittle though, because quoting an + argument makes the MSys based tool unescape backslashes where it shouldn't + (e.g. "a\b\\c\\\\d" becomes "a\b\c\\d" where it should stay as it was, + according to regular win32 command line parsing rules). + """ + result = [] + needquote = False + for arg in seq: + bs_buf = [] + + # Add a space to separate this argument from the others + if result: + result.append(" ") + + # This logic differs from upstream list2cmdline. + needquote = ( + (" " in arg) + or ("\t" in arg) + or ('"' in arg) + or ("[" in arg) + or (";" in arg) + or not arg + ) + if needquote: + result.append('"') + + for c in arg: + if c == "\\": + # Don't know if we need to double yet. + bs_buf.append(c) + elif c == '"': + # Double backslashes. + result.append("\\" * len(bs_buf) * 2) + bs_buf = [] + result.append('\\"') + else: + # Normal char + if bs_buf: + result.extend(bs_buf) + bs_buf = [] + result.append(c) + + # Add remaining backslashes, if any. + if bs_buf: + result.extend(bs_buf) + + if needquote: + result.extend(bs_buf) + result.append('"') + + return "".join(result) + + +# args are from 'export' or 'env' command. +# Skips the command, and parses its arguments. +# Modifies env accordingly. +# Returns copy of args without the command or its arguments. +def updateEnv(env, args): + arg_idx_next = len(args) + unset_next_env_var = False + for arg_idx, arg in enumerate(args[1:]): + # Support for the -u flag (unsetting) for env command + # e.g., env -u FOO -u BAR will remove both FOO and BAR + # from the environment. + if arg == "-u": + unset_next_env_var = True + continue + if unset_next_env_var: + unset_next_env_var = False + if arg in env.env: + del env.env[arg] + continue + + # Partition the string into KEY=VALUE. + key, eq, val = arg.partition("=") + # Stop if there was no equals. + if eq == "": + arg_idx_next = arg_idx + 1 + break + env.env[key] = val + return args[arg_idx_next:] + + +def executeBuiltinCd(cmd, shenv): + """executeBuiltinCd - Change the current directory.""" + if len(cmd.args) != 2: + raise InternalShellError(cmd, "'cd' supports only one argument") + # Update the cwd in the parent environment. + shenv.change_dir(cmd.args[1]) + # The cd builtin always succeeds. If the directory does not exist, the + # following Popen calls will fail instead. + return ShellCommandResult(cmd, "", "", 0, False) + + +def executeBuiltinPushd(cmd, shenv): + """executeBuiltinPushd - Change the current dir and save the old.""" + if len(cmd.args) != 2: + raise InternalShellError(cmd, "'pushd' supports only one argument") + shenv.dirStack.append(shenv.cwd) + shenv.change_dir(cmd.args[1]) + return ShellCommandResult(cmd, "", "", 0, False) + + +def executeBuiltinPopd(cmd, shenv): + """executeBuiltinPopd - Restore a previously saved working directory.""" + if len(cmd.args) != 1: + raise InternalShellError(cmd, "'popd' does not support arguments") + if not shenv.dirStack: + raise InternalShellError(cmd, "popd: directory stack empty") + shenv.cwd = shenv.dirStack.pop() + return ShellCommandResult(cmd, "", "", 0, False) + + +def executeBuiltinExport(cmd, shenv): + """executeBuiltinExport - Set an environment variable.""" + if len(cmd.args) != 2: + raise InternalShellError("'export' supports only one argument") + updateEnv(shenv, cmd.args) + return ShellCommandResult(cmd, "", "", 0, False) + + +def executeBuiltinEcho(cmd, shenv): + """Interpret a redirected echo or @echo command""" + opened_files = [] + stdin, stdout, stderr = processRedirects(cmd, subprocess.PIPE, shenv, opened_files) + if stdin != subprocess.PIPE or stderr != subprocess.PIPE: + raise InternalShellError( + cmd, f"stdin and stderr redirects not supported for {cmd.args[0]}" + ) + + # Some tests have un-redirected echo commands to help debug test failures. + # Buffer our output and return it to the caller. + is_redirected = True + encode = lambda x: x + if stdout == subprocess.PIPE: + is_redirected = False + stdout = StringIO() + elif kIsWindows: + # Reopen stdout in binary mode to avoid CRLF translation. The versions + # of echo we are replacing on Windows all emit plain LF, and the LLVM + # tests now depend on this. + # When we open as binary, however, this also means that we have to write + # 'bytes' objects to stdout instead of 'str' objects. + encode = lit.util.to_bytes + stdout = open(stdout.name, stdout.mode + "b") + opened_files.append((None, None, stdout, None)) + + # Implement echo flags. We only support -e and -n, and not yet in + # combination. We have to ignore unknown flags, because `echo "-D FOO"` + # prints the dash. + args = cmd.args[1:] + interpret_escapes = False + write_newline = True + while len(args) >= 1 and args[0] in ("-e", "-n"): + flag = args[0] + args = args[1:] + if flag == "-e": + interpret_escapes = True + elif flag == "-n": + write_newline = False + + def maybeUnescape(arg): + if not interpret_escapes: + return arg + + arg = lit.util.to_bytes(arg) + codec = "string_escape" if sys.version_info < (3, 0) else "unicode_escape" + return arg.decode(codec) + + if args: + for arg in args[:-1]: + stdout.write(encode(maybeUnescape(arg))) + stdout.write(encode(" ")) + stdout.write(encode(maybeUnescape(args[-1]))) + if write_newline: + stdout.write(encode("\n")) + + for (name, mode, f, path) in opened_files: + f.close() + + output = "" if is_redirected else stdout.getvalue() + return ShellCommandResult(cmd, output, "", 0, False) + + +def executeBuiltinMkdir(cmd, cmd_shenv): + """executeBuiltinMkdir - Create new directories.""" + args = expand_glob_expressions(cmd.args, cmd_shenv.cwd)[1:] + try: + opts, args = getopt.gnu_getopt(args, "p") + except getopt.GetoptError as err: + raise InternalShellError(cmd, "Unsupported: 'mkdir': %s" % str(err)) + + parent = False + for o, a in opts: + if o == "-p": + parent = True + else: + assert False, "unhandled option" + + if len(args) == 0: + raise InternalShellError(cmd, "Error: 'mkdir' is missing an operand") + + stderr = StringIO() + exitCode = 0 + for dir in args: + cwd = cmd_shenv.cwd + dir = to_unicode(dir) if kIsWindows else to_bytes(dir) + cwd = to_unicode(cwd) if kIsWindows else to_bytes(cwd) + if not os.path.isabs(dir): + dir = lit.util.abs_path_preserve_drive(os.path.join(cwd, dir)) + if parent: + lit.util.mkdir_p(dir) + else: + try: + lit.util.mkdir(dir) + except OSError as err: + stderr.write("Error: 'mkdir' command failed, %s\n" % str(err)) + exitCode = 1 + return ShellCommandResult(cmd, "", stderr.getvalue(), exitCode, False) + + +def executeBuiltinRm(cmd, cmd_shenv): + """executeBuiltinRm - Removes (deletes) files or directories.""" + args = expand_glob_expressions(cmd.args, cmd_shenv.cwd)[1:] + try: + opts, args = getopt.gnu_getopt(args, "frR", ["--recursive"]) + except getopt.GetoptError as err: + raise InternalShellError(cmd, "Unsupported: 'rm': %s" % str(err)) + + force = False + recursive = False + for o, a in opts: + if o == "-f": + force = True + elif o in ("-r", "-R", "--recursive"): + recursive = True + else: + assert False, "unhandled option" + + if len(args) == 0: + raise InternalShellError(cmd, "Error: 'rm' is missing an operand") + + def on_rm_error(func, path, exc_info): + # path contains the path of the file that couldn't be removed + # let's just assume that it's read-only and remove it. + os.chmod(path, stat.S_IMODE(os.stat(path).st_mode) | stat.S_IWRITE) + os.remove(path) + + stderr = StringIO() + exitCode = 0 + for path in args: + cwd = cmd_shenv.cwd + path = to_unicode(path) if kIsWindows else to_bytes(path) + cwd = to_unicode(cwd) if kIsWindows else to_bytes(cwd) + if not os.path.isabs(path): + path = lit.util.abs_path_preserve_drive(os.path.join(cwd, path)) + if force and not os.path.exists(path): + continue + try: + if os.path.isdir(path): + if not recursive: + stderr.write("Error: %s is a directory\n" % path) + exitCode = 1 + if platform.system() == "Windows": + # NOTE: use ctypes to access `SHFileOperationsW` on Windows to + # use the NT style path to get access to long file paths which + # cannot be removed otherwise. + from ctypes.wintypes import BOOL, HWND, LPCWSTR, UINT, WORD + from ctypes import addressof, byref, c_void_p, create_unicode_buffer + from ctypes import Structure + from ctypes import windll, WinError, POINTER + + class SHFILEOPSTRUCTW(Structure): + _fields_ = [ + ("hWnd", HWND), + ("wFunc", UINT), + ("pFrom", LPCWSTR), + ("pTo", LPCWSTR), + ("fFlags", WORD), + ("fAnyOperationsAborted", BOOL), + ("hNameMappings", c_void_p), + ("lpszProgressTitle", LPCWSTR), + ] + + FO_MOVE, FO_COPY, FO_DELETE, FO_RENAME = range(1, 5) + + FOF_SILENT = 4 + FOF_NOCONFIRMATION = 16 + FOF_NOCONFIRMMKDIR = 512 + FOF_NOERRORUI = 1024 + + FOF_NO_UI = ( + FOF_SILENT + | FOF_NOCONFIRMATION + | FOF_NOERRORUI + | FOF_NOCONFIRMMKDIR + ) + + SHFileOperationW = windll.shell32.SHFileOperationW + SHFileOperationW.argtypes = [POINTER(SHFILEOPSTRUCTW)] + + path = os.path.abspath(path) + + pFrom = create_unicode_buffer(path, len(path) + 2) + pFrom[len(path)] = pFrom[len(path) + 1] = "\0" + operation = SHFILEOPSTRUCTW( + wFunc=UINT(FO_DELETE), + pFrom=LPCWSTR(addressof(pFrom)), + fFlags=FOF_NO_UI, + ) + result = SHFileOperationW(byref(operation)) + if result: + raise WinError(result) + else: + shutil.rmtree(path, onerror=on_rm_error if force else None) + else: + if force and not os.access(path, os.W_OK): + os.chmod(path, stat.S_IMODE(os.stat(path).st_mode) | stat.S_IWRITE) + os.remove(path) + except OSError as err: + stderr.write("Error: 'rm' command failed, %s" % str(err)) + exitCode = 1 + return ShellCommandResult(cmd, "", stderr.getvalue(), exitCode, False) + + +def executeBuiltinColon(cmd, cmd_shenv): + """executeBuiltinColon - Discard arguments and exit with status 0.""" + return ShellCommandResult(cmd, "", "", 0, False) + + +def processRedirects(cmd, stdin_source, cmd_shenv, opened_files): + """Return the standard fds for cmd after applying redirects + + Returns the three standard file descriptors for the new child process. Each + fd may be an open, writable file object or a sentinel value from the + subprocess module. + """ + + # Apply the redirections, we use (N,) as a sentinel to indicate stdin, + # stdout, stderr for N equal to 0, 1, or 2 respectively. Redirects to or + # from a file are represented with a list [file, mode, file-object] + # where file-object is initially None. + redirects = [(0,), (1,), (2,)] + for (op, filename) in cmd.redirects: + if op == (">", 2): + redirects[2] = [filename, "w", None] + elif op == (">>", 2): + redirects[2] = [filename, "a", None] + elif op == (">&", 2) and filename in "012": + redirects[2] = redirects[int(filename)] + elif op == (">&",) or op == ("&>",): + redirects[1] = redirects[2] = [filename, "w", None] + elif op == (">",): + redirects[1] = [filename, "w", None] + elif op == (">>",): + redirects[1] = [filename, "a", None] + elif op == ("<",): + redirects[0] = [filename, "r", None] + else: + raise InternalShellError( + cmd, "Unsupported redirect: %r" % ((op, filename),) + ) + + # Open file descriptors in a second pass. + std_fds = [None, None, None] + for (index, r) in enumerate(redirects): + # Handle the sentinel values for defaults up front. + if isinstance(r, tuple): + if r == (0,): + fd = stdin_source + elif r == (1,): + if index == 0: + raise InternalShellError(cmd, "Unsupported redirect for stdin") + elif index == 1: + fd = subprocess.PIPE + else: + fd = subprocess.STDOUT + elif r == (2,): + if index != 2: + raise InternalShellError(cmd, "Unsupported redirect on stdout") + fd = subprocess.PIPE + else: + raise InternalShellError(cmd, "Bad redirect") + std_fds[index] = fd + continue + + (filename, mode, fd) = r + + # Check if we already have an open fd. This can happen if stdout and + # stderr go to the same place. + if fd is not None: + std_fds[index] = fd + continue + + redir_filename = None + name = expand_glob(filename, cmd_shenv.cwd) + if len(name) != 1: + raise InternalShellError( + cmd, "Unsupported: glob in " "redirect expanded to multiple files" + ) + name = name[0] + if kAvoidDevNull and name == kDevNull: + fd = tempfile.TemporaryFile(mode=mode) + elif kIsWindows and name == "/dev/tty": + # Simulate /dev/tty on Windows. + # "CON" is a special filename for the console. + fd = open("CON", mode) + else: + # Make sure relative paths are relative to the cwd. + redir_filename = os.path.join(cmd_shenv.cwd, name) + redir_filename = ( + to_unicode(redir_filename) if kIsWindows else to_bytes(redir_filename) + ) + fd = open(redir_filename, mode) + # Workaround a Win32 and/or subprocess bug when appending. + # + # FIXME: Actually, this is probably an instance of PR6753. + if mode == "a": + fd.seek(0, 2) + # Mutate the underlying redirect list so that we can redirect stdout + # and stderr to the same place without opening the file twice. + r[2] = fd + opened_files.append((filename, mode, fd) + (redir_filename,)) + std_fds[index] = fd + + return std_fds + + +def _executeShCmd(cmd, shenv, results, timeoutHelper): + if timeoutHelper.timeoutReached(): + # Prevent further recursion if the timeout has been hit + # as we should try avoid launching more processes. + return None + + if isinstance(cmd, ShUtil.Seq): + if cmd.op == ";": + res = _executeShCmd(cmd.lhs, shenv, results, timeoutHelper) + return _executeShCmd(cmd.rhs, shenv, results, timeoutHelper) + + if cmd.op == "&": + raise InternalShellError(cmd, "unsupported shell operator: '&'") + + if cmd.op == "||": + res = _executeShCmd(cmd.lhs, shenv, results, timeoutHelper) + if res != 0: + res = _executeShCmd(cmd.rhs, shenv, results, timeoutHelper) + return res + + if cmd.op == "&&": + res = _executeShCmd(cmd.lhs, shenv, results, timeoutHelper) + if res is None: + return res + + if res == 0: + res = _executeShCmd(cmd.rhs, shenv, results, timeoutHelper) + return res + + raise ValueError("Unknown shell command: %r" % cmd.op) + assert isinstance(cmd, ShUtil.Pipeline) + + procs = [] + proc_not_counts = [] + default_stdin = subprocess.PIPE + stderrTempFiles = [] + opened_files = [] + named_temp_files = [] + builtin_commands = set(["cat", "diff"]) + builtin_commands_dir = os.path.join( + os.path.dirname(os.path.abspath(__file__)), "builtin_commands" + ) + inproc_builtins = { + "cd": executeBuiltinCd, + "export": executeBuiltinExport, + "echo": executeBuiltinEcho, + "@echo": executeBuiltinEcho, + "mkdir": executeBuiltinMkdir, + "popd": executeBuiltinPopd, + "pushd": executeBuiltinPushd, + "rm": executeBuiltinRm, + ":": executeBuiltinColon, + } + # To avoid deadlock, we use a single stderr stream for piped + # output. This is null until we have seen some output using + # stderr. + for i, j in enumerate(cmd.commands): + # Reference the global environment by default. + cmd_shenv = shenv + args = list(j.args) + not_args = [] + not_count = 0 + not_crash = False + while True: + if args[0] == "env": + # Create a copy of the global environment and modify it for + # this one command. There might be multiple envs in a pipeline, + # and there might be multiple envs in a command (usually when + # one comes from a substitution): + # env FOO=1 llc < %s | env BAR=2 llvm-mc | FileCheck %s + # env FOO=1 %{another_env_plus_cmd} | FileCheck %s + if cmd_shenv is shenv: + cmd_shenv = ShellEnvironment(shenv.cwd, shenv.env) + args = updateEnv(cmd_shenv, args) + if not args: + raise InternalShellError(j, "Error: 'env' requires a" " subcommand") + elif args[0] == "not": + not_args.append(args.pop(0)) + not_count += 1 + if args and args[0] == "--crash": + not_args.append(args.pop(0)) + not_crash = True + if not args: + raise InternalShellError(j, "Error: 'not' requires a" " subcommand") + elif args[0] == "!": + not_args.append(args.pop(0)) + not_count += 1 + if not args: + raise InternalShellError(j, "Error: '!' requires a" " subcommand") + else: + break + + # Handle in-process builtins. + # + # Handle "echo" as a builtin if it is not part of a pipeline. This + # greatly speeds up tests that construct input files by repeatedly + # echo-appending to a file. + # FIXME: Standardize on the builtin echo implementation. We can use a + # temporary file to sidestep blocking pipe write issues. + inproc_builtin = inproc_builtins.get(args[0], None) + if inproc_builtin and (args[0] != "echo" or len(cmd.commands) == 1): + # env calling an in-process builtin is useless, so we take the safe + # approach of complaining. + if not cmd_shenv is shenv: + raise InternalShellError( + j, "Error: 'env' cannot call '{}'".format(args[0]) + ) + if not_crash: + raise InternalShellError( + j, "Error: 'not --crash' cannot call" " '{}'".format(args[0]) + ) + if len(cmd.commands) != 1: + raise InternalShellError( + j, + "Unsupported: '{}' cannot be part" " of a pipeline".format(args[0]), + ) + result = inproc_builtin(Command(args, j.redirects), cmd_shenv) + if not_count % 2: + result.exitCode = int(not result.exitCode) + result.command.args = j.args + results.append(result) + return result.exitCode + + # Resolve any out-of-process builtin command before adding back 'not' + # commands. + if args[0] in builtin_commands: + args.insert(0, sys.executable) + cmd_shenv.env["PYTHONPATH"] = os.path.dirname(os.path.abspath(__file__)) + args[1] = os.path.join(builtin_commands_dir, args[1] + ".py") + + # We had to search through the 'not' commands to find all the 'env' + # commands and any other in-process builtin command. We don't want to + # reimplement 'not' and its '--crash' here, so just push all 'not' + # commands back to be called as external commands. Because this + # approach effectively moves all 'env' commands up front, it relies on + # the assumptions that (1) environment variables are not intended to be + # relevant to 'not' commands and (2) the 'env' command should always + # blindly pass along the status it receives from any command it calls. + + # For plain negations, either 'not' without '--crash', or the shell + # operator '!', leave them out from the command to execute and + # invert the result code afterwards. + if not_crash: + args = not_args + args + not_count = 0 + else: + not_args = [] + + stdin, stdout, stderr = processRedirects( + j, default_stdin, cmd_shenv, opened_files + ) + + # If stderr wants to come from stdout, but stdout isn't a pipe, then put + # stderr on a pipe and treat it as stdout. + if stderr == subprocess.STDOUT and stdout != subprocess.PIPE: + stderr = subprocess.PIPE + stderrIsStdout = True + else: + stderrIsStdout = False + + # Don't allow stderr on a PIPE except for the last + # process, this could deadlock. + # + # FIXME: This is slow, but so is deadlock. + if stderr == subprocess.PIPE and j != cmd.commands[-1]: + stderr = tempfile.TemporaryFile(mode="w+b") + stderrTempFiles.append((i, stderr)) + + # Resolve the executable path ourselves. + executable = None + # For paths relative to cwd, use the cwd of the shell environment. + if args[0].startswith("."): + exe_in_cwd = os.path.join(cmd_shenv.cwd, args[0]) + if os.path.isfile(exe_in_cwd): + executable = exe_in_cwd + if not executable: + executable = lit.util.which(args[0], cmd_shenv.env["PATH"]) + if not executable: + raise InternalShellError(j, "%r: command not found" % args[0]) + + # Replace uses of /dev/null with temporary files. + if kAvoidDevNull: + # In Python 2.x, basestring is the base class for all string (including unicode) + # In Python 3.x, basestring no longer exist and str is always unicode + try: + str_type = basestring + except NameError: + str_type = str + for i, arg in enumerate(args): + if isinstance(arg, str_type) and kDevNull in arg: + f = tempfile.NamedTemporaryFile(delete=False) + f.close() + named_temp_files.append(f.name) + args[i] = arg.replace(kDevNull, f.name) + + # Expand all glob expressions + args = expand_glob_expressions(args, cmd_shenv.cwd) + + # On Windows, do our own command line quoting for better compatibility + # with some core utility distributions. + if kIsWindows: + args = quote_windows_command(args) + + try: + procs.append( + subprocess.Popen( + args, + cwd=cmd_shenv.cwd, + executable=executable, + stdin=stdin, + stdout=stdout, + stderr=stderr, + env=cmd_shenv.env, + close_fds=kUseCloseFDs, + universal_newlines=True, + errors="replace", + ) + ) + proc_not_counts.append(not_count) + # Let the helper know about this process + timeoutHelper.addProcess(procs[-1]) + except OSError as e: + raise InternalShellError( + j, "Could not create process ({}) due to {}".format(executable, e) + ) + + # Immediately close stdin for any process taking stdin from us. + if stdin == subprocess.PIPE: + procs[-1].stdin.close() + procs[-1].stdin = None + + # Update the current stdin source. + if stdout == subprocess.PIPE: + default_stdin = procs[-1].stdout + elif stderrIsStdout: + default_stdin = procs[-1].stderr + else: + default_stdin = subprocess.PIPE + + # Explicitly close any redirected files. We need to do this now because we + # need to release any handles we may have on the temporary files (important + # on Win32, for example). Since we have already spawned the subprocess, our + # handles have already been transferred so we do not need them anymore. + for (name, mode, f, path) in opened_files: + f.close() + + # FIXME: There is probably still deadlock potential here. Yawn. + procData = [None] * len(procs) + procData[-1] = procs[-1].communicate() + + for i in range(len(procs) - 1): + if procs[i].stdout is not None: + out = procs[i].stdout.read() + else: + out = "" + if procs[i].stderr is not None: + err = procs[i].stderr.read() + else: + err = "" + procData[i] = (out, err) + + # Read stderr out of the temp files. + for i, f in stderrTempFiles: + f.seek(0, 0) + procData[i] = (procData[i][0], f.read()) + f.close() + + exitCode = None + for i, (out, err) in enumerate(procData): + res = procs[i].wait() + # Detect Ctrl-C in subprocess. + if res == -signal.SIGINT: + raise KeyboardInterrupt + if proc_not_counts[i] % 2: + res = 1 if res == 0 else 0 + elif proc_not_counts[i] > 1: + res = 1 if res != 0 else 0 + + # Ensure the resulting output is always of string type. + try: + if out is None: + out = "" + else: + out = to_string(out.decode("utf-8", errors="replace")) + except: + out = str(out) + try: + if err is None: + err = "" + else: + err = to_string(err.decode("utf-8", errors="replace")) + except: + err = str(err) + + # Gather the redirected output files for failed commands. + output_files = [] + if res != 0: + for (name, mode, f, path) in sorted(opened_files): + if path is not None and mode in ("w", "a"): + try: + with open(path, "rb") as f: + data = f.read() + except: + data = None + if data is not None: + output_files.append((name, path, data)) + + results.append( + ShellCommandResult( + cmd.commands[i], + out, + err, + res, + timeoutHelper.timeoutReached(), + output_files, + ) + ) + if cmd.pipe_err: + # Take the last failing exit code from the pipeline. + if not exitCode or res != 0: + exitCode = res + else: + exitCode = res + + # Remove any named temporary files we created. + for f in named_temp_files: + try: + os.remove(f) + except OSError: + pass + + if cmd.negate: + exitCode = not exitCode + + return exitCode + + +def formatOutput(title, data, limit=None): + if not data.strip(): + return "" + if not limit is None and len(data) > limit: + data = data[:limit] + "\n...\n" + msg = "data was truncated" + else: + msg = "" + ndashes = 30 + # fmt: off + out = f"# .---{title}{'-' * (ndashes - 4 - len(title))}\n" + out += f"# | " + "\n# | ".join(data.splitlines()) + "\n" + out += f"# `---{msg}{'-' * (ndashes - 4 - len(msg))}\n" + # fmt: on + return out + + +# Always either returns the tuple (out, err, exitCode, timeoutInfo) or raises a +# ScriptFatal exception. +# +# If debug is True (the normal lit behavior), err is empty, and out contains an +# execution trace, including stdout and stderr shown per command executed. +# +# If debug is False (set by some custom lit test formats that call this +# function), out contains only stdout from the script, err contains only stderr +# from the script, and there is no execution trace. +def executeScriptInternal( + test, litConfig, tmpBase, commands, cwd, debug=True +) -> Tuple[str, str, int, Optional[str]]: + cmds = [] + for i, ln in enumerate(commands): + # Within lit, we try to always add '%dbg(...)' to command lines in order + # to maximize debuggability. However, custom lit test formats might not + # always add it, so add a generic debug message in that case. + match = re.fullmatch(kPdbgRegex, ln) + if match: + dbg = match.group(1) + command = match.group(2) + else: + dbg = "command line" + command = ln + if debug: + ln = f"@echo '# {dbg}' " + if command: + ln += f"&& @echo {shlex.quote(command.lstrip())} && {command}" + else: + ln += "has no command after substitutions" + else: + ln = command + try: + cmds.append( + ShUtil.ShParser(ln, litConfig.isWindows, test.config.pipefail).parse() + ) + except: + raise ScriptFatal( + f"shell parser error on {dbg}: {command.lstrip()}\n" + ) from None + + cmd = cmds[0] + for c in cmds[1:]: + cmd = ShUtil.Seq(cmd, "&&", c) + + results = [] + timeoutInfo = None + try: + shenv = ShellEnvironment(cwd, test.config.environment) + exitCode, timeoutInfo = executeShCmd( + cmd, shenv, results, timeout=litConfig.maxIndividualTestTime + ) + except InternalShellError: + e = sys.exc_info()[1] + exitCode = 127 + results.append(ShellCommandResult(e.command, "", e.message, exitCode, False)) + + out = err = "" + for i, result in enumerate(results): + if not debug: + out += result.stdout + err += result.stderr + continue + + # The purpose of an "@echo" command is merely to add a debugging message + # directly to lit's output. It is used internally by lit's internal + # shell and is not currently documented for use in lit tests. However, + # if someone misuses it (e.g., both "echo" and "@echo" complain about + # stdin redirection), produce the normal execution trace to facilitate + # debugging. + if ( + result.command.args[0] == "@echo" + and result.exitCode == 0 + and not result.stderr + and not result.outputFiles + and not result.timeoutReached + ): + out += result.stdout + continue + + # Write the command line that was run. Properly quote it. Leading + # "!" commands should not be quoted as that would indicate they are not + # the builtins. + out += "# executed command: " + nLeadingBangs = next( + (i for i, cmd in enumerate(result.command.args) if cmd != "!"), + len(result.command.args), + ) + out += "! " * nLeadingBangs + out += " ".join( + shlex.quote(str(s)) + for i, s in enumerate(result.command.args) + if i >= nLeadingBangs + ) + out += "\n" + + # If nothing interesting happened, move on. + if ( + litConfig.maxIndividualTestTime == 0 + and result.exitCode == 0 + and not result.stdout.strip() + and not result.stderr.strip() + ): + continue + + # Otherwise, something failed or was printed, show it. + + # Add the command output, if redirected. + for (name, path, data) in result.outputFiles: + data = to_string(data.decode("utf-8", errors="replace")) + out += formatOutput(f"redirected output from '{name}'", data, limit=1024) + if result.stdout.strip(): + out += formatOutput("command stdout", result.stdout) + if result.stderr.strip(): + out += formatOutput("command stderr", result.stderr) + if not result.stdout.strip() and not result.stderr.strip(): + out += "# note: command had no output on stdout or stderr\n" + + # Show the error conditions: + if result.exitCode != 0: + # On Windows, a negative exit code indicates a signal, and those are + # easier to recognize or look up if we print them in hex. + if litConfig.isWindows and (result.exitCode < 0 or result.exitCode > 255): + codeStr = hex(int(result.exitCode & 0xFFFFFFFF)).rstrip("L") + else: + codeStr = str(result.exitCode) + out += "# error: command failed with exit status: %s\n" % (codeStr,) + if litConfig.maxIndividualTestTime > 0 and result.timeoutReached: + out += "# error: command reached timeout: %s\n" % ( + str(result.timeoutReached), + ) + + return out, err, exitCode, timeoutInfo + + +def executeScript(test, litConfig, tmpBase, commands, cwd): + bashPath = litConfig.getBashPath() + isWin32CMDEXE = litConfig.isWindows and not bashPath + script = tmpBase + ".script" + if isWin32CMDEXE: + script += ".bat" + + # Write script file + mode = "w" + open_kwargs = {} + if litConfig.isWindows and not isWin32CMDEXE: + mode += "b" # Avoid CRLFs when writing bash scripts. + elif sys.version_info > (3, 0): + open_kwargs["encoding"] = "utf-8" + f = open(script, mode, **open_kwargs) + if isWin32CMDEXE: + for i, ln in enumerate(commands): + match = re.fullmatch(kPdbgRegex, ln) + if match: + command = match.group(2) + commands[i] = match.expand( + "echo '\\1' > nul && " if command else "echo '\\1' > nul" + ) + f.write("@echo on\n") + f.write("\n@if %ERRORLEVEL% NEQ 0 EXIT\n".join(commands)) + else: + for i, ln in enumerate(commands): + match = re.fullmatch(kPdbgRegex, ln) + if match: + dbg = match.group(1) + command = match.group(2) + # Echo the debugging diagnostic to stderr. + # + # For that echo command, use 'set' commands to suppress the + # shell's execution trace, which would just add noise. Suppress + # the shell's execution trace for the 'set' commands by + # redirecting their stderr to /dev/null. + if command: + msg = f"'{dbg}': {shlex.quote(command.lstrip())}" + else: + msg = f"'{dbg}' has no command after substitutions" + commands[i] = ( + f"{{ set +x; }} 2>/dev/null && " + f"echo {msg} >&2 && " + f"{{ set -x; }} 2>/dev/null" + ) + # Execute the command, if any. + # + # 'command' might be something like: + # + # subcmd & PID=$! + # + # In that case, we need something like: + # + # echo_dbg && { subcmd & PID=$!; } + # + # Without the '{ ...; }' enclosing the original 'command', '&' + # would put all of 'echo_dbg && subcmd' in the background. This + # would cause 'echo_dbg' to execute at the wrong time, and a + # later kill of $PID would target the wrong process. We have + # seen the latter manage to terminate the shell running lit. + if command: + commands[i] += f" && {{ {command}; }}" + if test.config.pipefail: + f.write(b"set -o pipefail;" if mode == "wb" else "set -o pipefail;") + f.write(b"set -x;" if mode == "wb" else "set -x;") + if sys.version_info > (3, 0) and mode == "wb": + f.write(bytes("{ " + "; } &&\n{ ".join(commands) + "; }", "utf-8")) + else: + f.write("{ " + "; } &&\n{ ".join(commands) + "; }") + f.write(b"\n" if mode == "wb" else "\n") + f.close() + + if isWin32CMDEXE: + command = ["cmd", "/c", script] + else: + if bashPath: + command = [bashPath, script] + else: + command = ["/bin/sh", script] + if litConfig.useValgrind: + # FIXME: Running valgrind on sh is overkill. We probably could just + # run on clang with no real loss. + command = litConfig.valgrindArgs + command + + try: + out, err, exitCode = lit.util.executeCommand( + command, + cwd=cwd, + env=test.config.environment, + timeout=litConfig.maxIndividualTestTime, + ) + return (out, err, exitCode, None) + except lit.util.ExecuteCommandTimeoutException as e: + return (e.out, e.err, e.exitCode, e.msg) + + +def parseIntegratedTestScriptCommands(source_path, keywords): + """ + parseIntegratedTestScriptCommands(source_path) -> commands + + Parse the commands in an integrated test script file into a list of + (line_number, command_type, line). + """ + + # This code is carefully written to be dual compatible with Python 2.5+ and + # Python 3 without requiring input files to always have valid codings. The + # trick we use is to open the file in binary mode and use the regular + # expression library to find the commands, with it scanning strings in + # Python2 and bytes in Python3. + # + # Once we find a match, we do require each script line to be decodable to + # UTF-8, so we convert the outputs to UTF-8 before returning. This way the + # remaining code can work with "strings" agnostic of the executing Python + # version. + + keywords_re = re.compile( + to_bytes("(%s)(.*)\n" % ("|".join(re.escape(k) for k in keywords),)) + ) + + f = open(source_path, "rb") + try: + # Read the entire file contents. + data = f.read() + + # Ensure the data ends with a newline. + if not data.endswith(to_bytes("\n")): + data = data + to_bytes("\n") + + # Iterate over the matches. + line_number = 1 + last_match_position = 0 + for match in keywords_re.finditer(data): + # Compute the updated line number by counting the intervening + # newlines. + match_position = match.start() + line_number += data.count( + to_bytes("\n"), last_match_position, match_position + ) + last_match_position = match_position + + # Convert the keyword and line to UTF-8 strings and yield the + # command. Note that we take care to return regular strings in + # Python 2, to avoid other code having to differentiate between the + # str and unicode types. + # + # Opening the file in binary mode prevented Windows \r newline + # characters from being converted to Unix \n newlines, so manually + # strip those from the yielded lines. + keyword, ln = match.groups() + yield ( + line_number, + to_string(keyword.decode("utf-8")), + to_string(ln.decode("utf-8").rstrip("\r")), + ) + finally: + f.close() + + +def getTempPaths(test): + """Get the temporary location, this is always relative to the test suite + root, not test source root.""" + execpath = test.getExecPath() + execdir, execbase = os.path.split(execpath) + tmpDir = os.path.join(execdir, "Output") + tmpBase = os.path.join(tmpDir, execbase) + return tmpDir, tmpBase + + +def colonNormalizePath(path): + if kIsWindows: + return re.sub(r"^(.):", r"\1", path.replace("\\", "/")) + else: + assert path[0] == "/" + return path[1:] + + +def getDefaultSubstitutions(test, tmpDir, tmpBase, normalize_slashes=False): + sourcepath = test.getSourcePath() + sourcedir = os.path.dirname(sourcepath) + + # Normalize slashes, if requested. + if normalize_slashes: + sourcepath = sourcepath.replace("\\", "/") + sourcedir = sourcedir.replace("\\", "/") + tmpDir = tmpDir.replace("\\", "/") + tmpBase = tmpBase.replace("\\", "/") + + substitutions = [] + substitutions.extend(test.config.substitutions) + tmpName = tmpBase + ".tmp" + baseName = os.path.basename(tmpBase) + + substitutions.append(("%{pathsep}", os.pathsep)) + substitutions.append(("%basename_t", baseName)) + + substitutions.extend( + [ + ("%{fs-src-root}", pathlib.Path(sourcedir).anchor), + ("%{fs-tmp-root}", pathlib.Path(tmpBase).anchor), + ("%{fs-sep}", os.path.sep), + ] + ) + + substitutions.append(("%/et", tmpName.replace("\\", "\\\\\\\\\\\\\\\\"))) + + def regex_escape(s): + s = s.replace("@", r"\@") + s = s.replace("&", r"\&") + return s + + path_substitutions = [ + ("s", sourcepath), ("S", sourcedir), ("p", sourcedir), + ("t", tmpName), ("T", tmpDir) + ] + for path_substitution in path_substitutions: + letter = path_substitution[0] + path = path_substitution[1] + + # Original path variant + substitutions.append(("%" + letter, path)) + + # Normalized path separator variant + substitutions.append(("%/" + letter, path.replace("\\", "/"))) + + # realpath variants + # Windows paths with substitute drives are not expanded by default + # as they are used to avoid MAX_PATH issues, but sometimes we do + # need the fully expanded path. + real_path = os.path.realpath(path) + substitutions.append(("%{" + letter + ":real}", real_path)) + substitutions.append(("%{/" + letter + ":real}", + real_path.replace("\\", "/"))) + + # "%{/[STpst]:regex_replacement}" should be normalized like + # "%/[STpst]" but we're also in a regex replacement context + # of a s@@@ regex. + substitutions.append( + ("%{/" + letter + ":regex_replacement}", + regex_escape(path.replace("\\", "/")))) + + # "%:[STpst]" are normalized paths without colons and without + # a leading slash. + substitutions.append(("%:" + letter, colonNormalizePath(path))) + + return substitutions + + +def _memoize(f): + cache = {} # Intentionally unbounded, see applySubstitutions() + + def memoized(x): + if x not in cache: + cache[x] = f(x) + return cache[x] + + return memoized + + +@_memoize +def _caching_re_compile(r): + return re.compile(r) + + +class ExpandableScriptDirective(object): + """ + Common interface for lit directives for which any lit substitutions must be + expanded to produce the shell script. It includes directives (e.g., 'RUN:') + specifying shell commands that might have lit substitutions to be expanded. + It also includes lit directives (e.g., 'DEFINE:') that adjust substitutions. + + start_line_number: The directive's starting line number. + end_line_number: The directive's ending line number, which is + start_line_number if the directive has no line continuations. + keyword: The keyword that specifies the directive. For example, 'RUN:'. + """ + + def __init__(self, start_line_number, end_line_number, keyword): + # Input line number where the directive starts. + self.start_line_number = start_line_number + # Input line number where the directive ends. + self.end_line_number = end_line_number + # The keyword used to indicate the directive. + self.keyword = keyword + + def add_continuation(self, line_number, keyword, line): + """ + Add a continuation line to this directive and return True, or do nothing + and return False if the specified line is not a continuation for this + directive (e.g., previous line does not end in '\', or keywords do not + match). + + line_number: The line number for the continuation line. + keyword: The keyword that specifies the continuation line. For example, + 'RUN:'. + line: The content of the continuation line after the keyword. + """ + assert False, "expected method to be called on derived class" + + def needs_continuation(self): + """ + Does this directive require a continuation line? + + '\' is documented as indicating a line continuation even if whitespace + separates it from the newline. It looks like a line continuation, and + it would be confusing if it didn't behave as one. + """ + assert False, "expected method to be called on derived class" + + def get_location(self): + """ + Get a phrase describing the line or range of lines so far included by + this directive and any line continuations. + """ + if self.start_line_number == self.end_line_number: + return f"at line {self.start_line_number}" + return f"from line {self.start_line_number} to {self.end_line_number}" + + +class CommandDirective(ExpandableScriptDirective): + """ + A lit directive taking a shell command line. For example, + 'RUN: echo hello world'. + + command: The content accumulated so far from the directive and its + continuation lines. + """ + + def __init__(self, start_line_number, end_line_number, keyword, line): + super().__init__(start_line_number, end_line_number, keyword) + self.command = line.rstrip() + + def add_continuation(self, line_number, keyword, line): + if keyword != self.keyword or not self.needs_continuation(): + return False + self.command = self.command[:-1] + line.rstrip() + self.end_line_number = line_number + return True + + def needs_continuation(self): + # Trailing whitespace is stripped immediately when each line is added, + # so '\' is never hidden here. + return self.command[-1] == "\\" + + +class SubstDirective(ExpandableScriptDirective): + """ + A lit directive taking a substitution definition or redefinition. For + example, 'DEFINE: %{name} = value'. + + new_subst: True if this directive defines a new substitution. False if it + redefines an existing substitution. + body: The unparsed content accumulated so far from the directive and its + continuation lines. + name: The substitution's name, or None if more continuation lines are still + required. + value: The substitution's value, or None if more continuation lines are + still required. + """ + + def __init__(self, start_line_number, end_line_number, keyword, new_subst, line): + super().__init__(start_line_number, end_line_number, keyword) + self.new_subst = new_subst + self.body = line + self.name = None + self.value = None + self._parse_body() + + def add_continuation(self, line_number, keyword, line): + if keyword != self.keyword or not self.needs_continuation(): + return False + if not line.strip(): + raise ValueError("Substitution's continuation is empty") + # Append line. Replace the '\' and any adjacent whitespace with a + # single space. + self.body = self.body.rstrip()[:-1].rstrip() + " " + line.lstrip() + self.end_line_number = line_number + self._parse_body() + return True + + def needs_continuation(self): + return self.body.rstrip()[-1:] == "\\" + + def _parse_body(self): + """ + If no more line continuations are required, parse all the directive's + accumulated lines in order to identify the substitution's name and full + value, and raise an exception if invalid. + """ + if self.needs_continuation(): + return + + # Extract the left-hand side and value, and discard any whitespace + # enclosing each. + parts = self.body.split("=", 1) + if len(parts) == 1: + raise ValueError("Substitution's definition does not contain '='") + self.name = parts[0].strip() + self.value = parts[1].strip() + + # Check the substitution's name. + # + # Do not extend this to permit '.' or any sequence that's special in a + # python pattern. We could escape that automatically for + # DEFINE/REDEFINE directives in test files. However, lit configuration + # file authors would still have to remember to escape them manually in + # substitution names but not in values. Moreover, the manually chosen + # and automatically chosen escape sequences would have to be consistent + # (e.g., '\.' vs. '[.]') in order for REDEFINE to successfully redefine + # a substitution previously defined by a lit configuration file. All + # this seems too error prone and confusing to be worthwhile. If you + # want your name to express structure, use ':' instead of '.'. + # + # Actually, '{' and '}' are special if they contain only digits possibly + # separated by a comma. Requiring a leading letter avoids that. + if not re.fullmatch(r"%{[_a-zA-Z][-_:0-9a-zA-Z]*}", self.name): + raise ValueError( + f"Substitution name '{self.name}' is malformed as it must " + f"start with '%{{', it must end with '}}', and the rest must " + f"start with a letter or underscore and contain only " + f"alphanumeric characters, hyphens, underscores, and colons" + ) + + def adjust_substitutions(self, substitutions): + """ + Modify the specified substitution list as specified by this directive. + """ + assert ( + not self.needs_continuation() + ), "expected directive continuations to be parsed before applying" + value_repl = self.value.replace("\\", "\\\\") + existing = [i for i, subst in enumerate(substitutions) if self.name in subst[0]] + existing_res = "".join( + "\nExisting pattern: " + substitutions[i][0] for i in existing + ) + if self.new_subst: + if existing: + raise ValueError( + f"Substitution whose pattern contains '{self.name}' is " + f"already defined before '{self.keyword}' directive " + f"{self.get_location()}" + f"{existing_res}" + ) + substitutions.insert(0, (self.name, value_repl)) + return + if len(existing) > 1: + raise ValueError( + f"Multiple substitutions whose patterns contain '{self.name}' " + f"are defined before '{self.keyword}' directive " + f"{self.get_location()}" + f"{existing_res}" + ) + if not existing: + raise ValueError( + f"No substitution for '{self.name}' is defined before " + f"'{self.keyword}' directive {self.get_location()}" + ) + if substitutions[existing[0]][0] != self.name: + raise ValueError( + f"Existing substitution whose pattern contains '{self.name}' " + f"does not have the pattern specified by '{self.keyword}' " + f"directive {self.get_location()}\n" + f"Expected pattern: {self.name}" + f"{existing_res}" + ) + substitutions[existing[0]] = (self.name, value_repl) + + +def applySubstitutions(script, substitutions, conditions={}, recursion_limit=None): + """ + Apply substitutions to the script. Allow full regular expression syntax. + Replace each matching occurrence of regular expression pattern a with + substitution b in line ln. + + If a substitution expands into another substitution, it is expanded + recursively until the line has no more expandable substitutions. If + the line can still can be substituted after being substituted + `recursion_limit` times, it is an error. If the `recursion_limit` is + `None` (the default), no recursive substitution is performed at all. + """ + + # We use #_MARKER_# to hide %% while we do the other substitutions. + def escapePercents(ln): + return _caching_re_compile("%%").sub("#_MARKER_#", ln) + + def unescapePercents(ln): + return _caching_re_compile("#_MARKER_#").sub("%", ln) + + def substituteIfElse(ln): + # early exit to avoid wasting time on lines without + # conditional substitutions + if ln.find("%if ") == -1: + return ln + + def tryParseIfCond(ln): + # space is important to not conflict with other (possible) + # substitutions + if not ln.startswith("%if "): + return None, ln + ln = ln[4:] + + # stop at '%{' + match = _caching_re_compile("%{").search(ln) + if not match: + raise ValueError("'%{' is missing for %if substitution") + cond = ln[: match.start()] + + # eat '%{' as well + ln = ln[match.end() :] + return cond, ln + + def tryParseElse(ln): + match = _caching_re_compile(r"^\s*%else\s*(%{)?").search(ln) + if not match: + return False, ln + if not match.group(1): + raise ValueError("'%{' is missing for %else substitution") + return True, ln[match.end() :] + + def tryParseEnd(ln): + if ln.startswith("%}"): + return True, ln[2:] + return False, ln + + def parseText(ln, isNested): + # parse everything until %if, or %} if we're parsing a + # nested expression. + match = _caching_re_compile( + "(.*?)(?:%if|%})" if isNested else "(.*?)(?:%if)" + ).search(ln) + if not match: + # there is no terminating pattern, so treat the whole + # line as text + return ln, "" + text_end = match.end(1) + return ln[:text_end], ln[text_end:] + + def parseRecursive(ln, isNested): + result = "" + while len(ln): + if isNested: + found_end, _ = tryParseEnd(ln) + if found_end: + break + + # %if cond %{ branch_if %} %else %{ branch_else %} + cond, ln = tryParseIfCond(ln) + if cond: + branch_if, ln = parseRecursive(ln, isNested=True) + found_end, ln = tryParseEnd(ln) + if not found_end: + raise ValueError("'%}' is missing for %if substitution") + + branch_else = "" + found_else, ln = tryParseElse(ln) + if found_else: + branch_else, ln = parseRecursive(ln, isNested=True) + found_end, ln = tryParseEnd(ln) + if not found_end: + raise ValueError("'%}' is missing for %else substitution") + + if BooleanExpression.evaluate(cond, conditions): + result += branch_if + else: + result += branch_else + continue + + # The rest is handled as plain text. + text, ln = parseText(ln, isNested) + result += text + + return result, ln + + result, ln = parseRecursive(ln, isNested=False) + assert len(ln) == 0 + return result + + def processLine(ln): + # Apply substitutions + ln = substituteIfElse(escapePercents(ln)) + for a, b in substitutions: + if kIsWindows: + b = b.replace("\\", "\\\\") + # re.compile() has a built-in LRU cache with 512 entries. In some + # test suites lit ends up thrashing that cache, which made e.g. + # check-llvm run 50% slower. Use an explicit, unbounded cache + # to prevent that from happening. Since lit is fairly + # short-lived, since the set of substitutions is fairly small, and + # since thrashing has such bad consequences, not bounding the cache + # seems reasonable. + ln = _caching_re_compile(a).sub(str(b), escapePercents(ln)) + + # Strip the trailing newline and any extra whitespace. + return ln.strip() + + def processLineToFixedPoint(ln): + assert isinstance(recursion_limit, int) and recursion_limit >= 0 + origLine = ln + steps = 0 + processed = processLine(ln) + while processed != ln and steps < recursion_limit: + ln = processed + processed = processLine(ln) + steps += 1 + + if processed != ln: + raise ValueError( + "Recursive substitution of '%s' did not complete " + "in the provided recursion limit (%s)" % (origLine, recursion_limit) + ) + + return processed + + process = processLine if recursion_limit is None else processLineToFixedPoint + output = [] + for directive in script: + if isinstance(directive, SubstDirective): + directive.adjust_substitutions(substitutions) + else: + if isinstance(directive, CommandDirective): + line = directive.command + else: + # Can come from preamble_commands. + assert isinstance(directive, str) + line = directive + output.append(unescapePercents(process(line))) + + return output + + +class ParserKind(object): + """ + An enumeration representing the style of an integrated test keyword or + command. + + TAG: A keyword taking no value. Ex 'END.' + COMMAND: A keyword taking a list of shell commands. Ex 'RUN:' + LIST: A keyword taking a comma-separated list of values. + SPACE_LIST: A keyword taking a space-separated list of values. + BOOLEAN_EXPR: A keyword taking a comma-separated list of + boolean expressions. Ex 'XFAIL:' + INTEGER: A keyword taking a single integer. Ex 'ALLOW_RETRIES:' + CUSTOM: A keyword with custom parsing semantics. + DEFINE: A keyword taking a new lit substitution definition. Ex + 'DEFINE: %{name}=value' + REDEFINE: A keyword taking a lit substitution redefinition. Ex + 'REDEFINE: %{name}=value' + """ + + TAG = 0 + COMMAND = 1 + LIST = 2 + SPACE_LIST = 3 + BOOLEAN_EXPR = 4 + INTEGER = 5 + CUSTOM = 6 + DEFINE = 7 + REDEFINE = 8 + + @staticmethod + def allowedKeywordSuffixes(value): + return { + ParserKind.TAG: ["."], + ParserKind.COMMAND: [":"], + ParserKind.LIST: [":"], + ParserKind.SPACE_LIST: [":"], + ParserKind.BOOLEAN_EXPR: [":"], + ParserKind.INTEGER: [":"], + ParserKind.CUSTOM: [":", "."], + ParserKind.DEFINE: [":"], + ParserKind.REDEFINE: [":"], + }[value] + + @staticmethod + def str(value): + return { + ParserKind.TAG: "TAG", + ParserKind.COMMAND: "COMMAND", + ParserKind.LIST: "LIST", + ParserKind.SPACE_LIST: "SPACE_LIST", + ParserKind.BOOLEAN_EXPR: "BOOLEAN_EXPR", + ParserKind.INTEGER: "INTEGER", + ParserKind.CUSTOM: "CUSTOM", + ParserKind.DEFINE: "DEFINE", + ParserKind.REDEFINE: "REDEFINE", + }[value] + + +class IntegratedTestKeywordParser(object): + """A parser for LLVM/Clang style integrated test scripts. + + keyword: The keyword to parse for. It must end in either '.' or ':'. + kind: An value of ParserKind. + parser: A custom parser. This value may only be specified with + ParserKind.CUSTOM. + """ + + def __init__(self, keyword, kind, parser=None, initial_value=None): + allowedSuffixes = ParserKind.allowedKeywordSuffixes(kind) + if len(keyword) == 0 or keyword[-1] not in allowedSuffixes: + if len(allowedSuffixes) == 1: + raise ValueError( + "Keyword '%s' of kind '%s' must end in '%s'" + % (keyword, ParserKind.str(kind), allowedSuffixes[0]) + ) + else: + raise ValueError( + "Keyword '%s' of kind '%s' must end in " + " one of '%s'" + % (keyword, ParserKind.str(kind), " ".join(allowedSuffixes)) + ) + + if parser is not None and kind != ParserKind.CUSTOM: + raise ValueError( + "custom parsers can only be specified with " "ParserKind.CUSTOM" + ) + self.keyword = keyword + self.kind = kind + self.parsed_lines = [] + self.value = initial_value + self.parser = parser + + if kind == ParserKind.COMMAND: + self.parser = lambda line_number, line, output: self._handleCommand( + line_number, line, output, self.keyword + ) + elif kind == ParserKind.LIST: + self.parser = self._handleList + elif kind == ParserKind.SPACE_LIST: + self.parser = self._handleSpaceList + elif kind == ParserKind.BOOLEAN_EXPR: + self.parser = self._handleBooleanExpr + elif kind == ParserKind.INTEGER: + self.parser = self._handleSingleInteger + elif kind == ParserKind.TAG: + self.parser = self._handleTag + elif kind == ParserKind.CUSTOM: + if parser is None: + raise ValueError("ParserKind.CUSTOM requires a custom parser") + self.parser = parser + elif kind == ParserKind.DEFINE: + self.parser = lambda line_number, line, output: self._handleSubst( + line_number, line, output, self.keyword, new_subst=True + ) + elif kind == ParserKind.REDEFINE: + self.parser = lambda line_number, line, output: self._handleSubst( + line_number, line, output, self.keyword, new_subst=False + ) + else: + raise ValueError("Unknown kind '%s'" % kind) + + def parseLine(self, line_number, line): + try: + self.parsed_lines += [(line_number, line)] + self.value = self.parser(line_number, line, self.value) + except ValueError as e: + raise ValueError( + str(e) + + ("\nin %s directive on test line %d" % (self.keyword, line_number)) + ) + + def getValue(self): + return self.value + + @staticmethod + def _handleTag(line_number, line, output): + """A helper for parsing TAG type keywords""" + return not line.strip() or output + + @staticmethod + def _substituteLineNumbers(line_number, line): + line = re.sub(r"%\(line\)", str(line_number), line) + + def replace_line_number(match): + if match.group(1) == "+": + return str(line_number + int(match.group(2))) + if match.group(1) == "-": + return str(line_number - int(match.group(2))) + + return re.sub(r"%\(line *([\+-]) *(\d+)\)", replace_line_number, line) + + @classmethod + def _handleCommand(cls, line_number, line, output, keyword): + """A helper for parsing COMMAND type keywords""" + # Substitute line number expressions. + line = cls._substituteLineNumbers(line_number, line) + + # Collapse lines with trailing '\\', or add line with line number to + # start a new pipeline. + if not output or not output[-1].add_continuation(line_number, keyword, line): + if output is None: + output = [] + line = buildPdbgCommand(f"{keyword} at line {line_number}", line) + output.append(CommandDirective(line_number, line_number, keyword, line)) + return output + + @staticmethod + def _handleList(line_number, line, output): + """A parser for LIST type keywords""" + if output is None: + output = [] + output.extend([s.strip() for s in line.split(",")]) + return output + + @staticmethod + def _handleSpaceList(line_number, line, output): + """A parser for SPACE_LIST type keywords""" + if output is None: + output = [] + output.extend([s.strip() for s in line.split(" ") if s.strip() != ""]) + return output + + @staticmethod + def _handleSingleInteger(line_number, line, output): + """A parser for INTEGER type keywords""" + if output is None: + output = [] + try: + n = int(line) + except ValueError: + raise ValueError( + "INTEGER parser requires the input to be an integer (got {})".format( + line + ) + ) + output.append(n) + return output + + @staticmethod + def _handleBooleanExpr(line_number, line, output): + """A parser for BOOLEAN_EXPR type keywords""" + parts = [s.strip() for s in line.split(",") if s.strip() != ""] + if output and output[-1][-1] == "\\": + output[-1] = output[-1][:-1] + parts[0] + del parts[0] + if output is None: + output = [] + output.extend(parts) + # Evaluate each expression to verify syntax. + # We don't want any results, just the raised ValueError. + for s in output: + if s != "*" and not s.endswith("\\"): + BooleanExpression.evaluate(s, []) + return output + + @classmethod + def _handleSubst(cls, line_number, line, output, keyword, new_subst): + """A parser for DEFINE and REDEFINE type keywords""" + line = cls._substituteLineNumbers(line_number, line) + if output and output[-1].add_continuation(line_number, keyword, line): + return output + if output is None: + output = [] + output.append( + SubstDirective(line_number, line_number, keyword, new_subst, line) + ) + return output + + +def _parseKeywords(sourcepath, additional_parsers=[], require_script=True): + """_parseKeywords + + Scan an LLVM/Clang style integrated test script and extract all the lines + pertaining to a special parser. This includes 'RUN', 'XFAIL', 'REQUIRES', + 'UNSUPPORTED', 'ALLOW_RETRIES', 'END', 'DEFINE', 'REDEFINE', as well as + other specified custom parsers. + + Returns a dictionary mapping each custom parser to its value after + parsing the test. + """ + # Install the built-in keyword parsers. + script = [] + builtin_parsers = [ + IntegratedTestKeywordParser("RUN:", ParserKind.COMMAND, initial_value=script), + IntegratedTestKeywordParser("XFAIL:", ParserKind.BOOLEAN_EXPR), + IntegratedTestKeywordParser("REQUIRES:", ParserKind.BOOLEAN_EXPR), + IntegratedTestKeywordParser("UNSUPPORTED:", ParserKind.BOOLEAN_EXPR), + IntegratedTestKeywordParser("ALLOW_RETRIES:", ParserKind.INTEGER), + IntegratedTestKeywordParser("END.", ParserKind.TAG), + IntegratedTestKeywordParser("DEFINE:", ParserKind.DEFINE, initial_value=script), + IntegratedTestKeywordParser( + "REDEFINE:", ParserKind.REDEFINE, initial_value=script + ), + ] + keyword_parsers = {p.keyword: p for p in builtin_parsers} + + # Install user-defined additional parsers. + for parser in additional_parsers: + if not isinstance(parser, IntegratedTestKeywordParser): + raise ValueError( + "Additional parser must be an instance of " + "IntegratedTestKeywordParser" + ) + if parser.keyword in keyword_parsers: + raise ValueError("Parser for keyword '%s' already exists" % parser.keyword) + keyword_parsers[parser.keyword] = parser + + # Collect the test lines from the script. + for line_number, command_type, ln in parseIntegratedTestScriptCommands( + sourcepath, keyword_parsers.keys() + ): + parser = keyword_parsers[command_type] + parser.parseLine(line_number, ln) + if command_type == "END." and parser.getValue() is True: + break + + # Verify the script contains a run line. + if require_script and not any( + isinstance(directive, CommandDirective) for directive in script + ): + raise ValueError("Test has no 'RUN:' line") + + # Check for unterminated run or subst lines. + # + # If, after a line continuation for one kind of directive (e.g., 'RUN:', + # 'DEFINE:', 'REDEFINE:') in script, the next directive in script is a + # different kind, then the '\\' remains on the former, and we report it + # here. + for directive in script: + if directive.needs_continuation(): + raise ValueError( + f"Test has unterminated '{directive.keyword}' " + f"directive (with '\\') " + f"{directive.get_location()}" + ) + + # Check boolean expressions for unterminated lines. + for key in keyword_parsers: + kp = keyword_parsers[key] + if kp.kind != ParserKind.BOOLEAN_EXPR: + continue + value = kp.getValue() + if value and value[-1][-1] == "\\": + raise ValueError( + "Test has unterminated '{key}' lines (with '\\')".format(key=key) + ) + + # Make sure there's at most one ALLOW_RETRIES: line + allowed_retries = keyword_parsers["ALLOW_RETRIES:"].getValue() + if allowed_retries and len(allowed_retries) > 1: + raise ValueError("Test has more than one ALLOW_RETRIES lines") + + return {p.keyword: p.getValue() for p in keyword_parsers.values()} + + +def parseIntegratedTestScript(test, additional_parsers=[], require_script=True): + """parseIntegratedTestScript - Scan an LLVM/Clang style integrated test + script and extract the lines to 'RUN' as well as 'XFAIL', 'REQUIRES', + 'UNSUPPORTED' and 'ALLOW_RETRIES' information into the given test. + + If additional parsers are specified then the test is also scanned for the + keywords they specify and all matches are passed to the custom parser. + + If 'require_script' is False an empty script + may be returned. This can be used for test formats where the actual script + is optional or ignored. + """ + # Parse the test sources and extract test properties + try: + parsed = _parseKeywords( + test.getSourcePath(), additional_parsers, require_script + ) + except ValueError as e: + return lit.Test.Result(Test.UNRESOLVED, str(e)) + script = parsed["RUN:"] or [] + assert parsed["DEFINE:"] == script + assert parsed["REDEFINE:"] == script + test.xfails += parsed["XFAIL:"] or [] + test.requires += parsed["REQUIRES:"] or [] + test.unsupported += parsed["UNSUPPORTED:"] or [] + if parsed["ALLOW_RETRIES:"]: + test.allowed_retries = parsed["ALLOW_RETRIES:"][0] + + # Enforce REQUIRES: + missing_required_features = test.getMissingRequiredFeatures() + if missing_required_features: + msg = ", ".join(missing_required_features) + return lit.Test.Result( + Test.UNSUPPORTED, + "Test requires the following unavailable " "features: %s" % msg, + ) + + # Enforce UNSUPPORTED: + unsupported_features = test.getUnsupportedFeatures() + if unsupported_features: + msg = ", ".join(unsupported_features) + return lit.Test.Result( + Test.UNSUPPORTED, + "Test does not support the following features " "and/or targets: %s" % msg, + ) + + # Enforce limit_to_features. + if not test.isWithinFeatureLimits(): + msg = ", ".join(test.config.limit_to_features) + return lit.Test.Result( + Test.UNSUPPORTED, + "Test does not require any of the features " + "specified in limit_to_features: %s" % msg, + ) + + return script + + +def _runShTest(test, litConfig, useExternalSh, script, tmpBase) -> lit.Test.Result: + # Always returns the tuple (out, err, exitCode, timeoutInfo, status). + def runOnce( + execdir, + ) -> Tuple[str, str, int, Optional[str], Test.ResultCode]: + # script is modified below (for litConfig.per_test_coverage, and for + # %dbg expansions). runOnce can be called multiple times, but applying + # the modifications multiple times can corrupt script, so always modify + # a copy. + scriptCopy = script[:] + # Set unique LLVM_PROFILE_FILE for each run command + if litConfig.per_test_coverage: + # Extract the test case name from the test object, and remove the + # file extension. + test_case_name = test.path_in_suite[-1] + test_case_name = test_case_name.rsplit(".", 1)[0] + coverage_index = 0 # Counter for coverage file index + for i, ln in enumerate(scriptCopy): + match = re.fullmatch(kPdbgRegex, ln) + if match: + dbg = match.group(1) + command = match.group(2) + else: + command = ln + profile = f"{test_case_name}{coverage_index}.profraw" + coverage_index += 1 + command = f"export LLVM_PROFILE_FILE={profile}; {command}" + if match: + command = buildPdbgCommand(dbg, command) + scriptCopy[i] = command + + try: + if useExternalSh: + res = executeScript(test, litConfig, tmpBase, scriptCopy, execdir) + else: + res = executeScriptInternal( + test, litConfig, tmpBase, scriptCopy, execdir + ) + except ScriptFatal as e: + out = f"# " + "\n# ".join(str(e).splitlines()) + "\n" + return out, "", 1, None, Test.UNRESOLVED + + out, err, exitCode, timeoutInfo = res + if exitCode == 0: + status = Test.PASS + else: + if timeoutInfo is None: + status = Test.FAIL + else: + status = Test.TIMEOUT + return out, err, exitCode, timeoutInfo, status + + # Create the output directory if it does not already exist. + lit.util.mkdir_p(os.path.dirname(tmpBase)) + + # Re-run failed tests up to test.allowed_retries times. + execdir = os.path.dirname(test.getExecPath()) + attempts = test.allowed_retries + 1 + for i in range(attempts): + res = runOnce(execdir) + out, err, exitCode, timeoutInfo, status = res + if status != Test.FAIL: + break + + # If we had to run the test more than once, count it as a flaky pass. These + # will be printed separately in the test summary. + if i > 0 and status == Test.PASS: + status = Test.FLAKYPASS + + # Form the output log. + output = f"Exit Code: {exitCode}\n" + + if timeoutInfo is not None: + output += """Timeout: %s\n""" % (timeoutInfo,) + output += "\n" + + # Append the outputs, if present. + if out: + output += """Command Output (stdout):\n--\n%s\n--\n""" % (out,) + if err: + output += """Command Output (stderr):\n--\n%s\n--\n""" % (err,) + + return lit.Test.Result(status, output) + + +def executeShTest( + test, litConfig, useExternalSh, extra_substitutions=[], preamble_commands=[] +): + if test.config.unsupported: + return lit.Test.Result(Test.UNSUPPORTED, "Test is unsupported") + + script = list(preamble_commands) + script = [buildPdbgCommand(f"preamble command line", ln) for ln in script] + + parsed = parseIntegratedTestScript(test, require_script=not script) + if isinstance(parsed, lit.Test.Result): + return parsed + script += parsed + + if litConfig.noExecute: + return lit.Test.Result(Test.PASS) + + tmpDir, tmpBase = getTempPaths(test) + substitutions = list(extra_substitutions) + substitutions += getDefaultSubstitutions( + test, tmpDir, tmpBase, normalize_slashes=useExternalSh + ) + conditions = {feature: True for feature in test.config.available_features} + script = applySubstitutions( + script, + substitutions, + conditions, + recursion_limit=test.config.recursiveExpansionLimit, + ) + + return _runShTest(test, litConfig, useExternalSh, script, tmpBase) diff --git a/wemm/lib/python3.10/site-packages/lit/TestTimes.py b/wemm/lib/python3.10/site-packages/lit/TestTimes.py new file mode 100644 index 0000000000000000000000000000000000000000..a2c0e0527b84bc8b457d3dcdc89fc59114441297 --- /dev/null +++ b/wemm/lib/python3.10/site-packages/lit/TestTimes.py @@ -0,0 +1,40 @@ +import os + + +def read_test_times(suite): + test_times = {} + test_times_file = os.path.join(suite.exec_root, ".lit_test_times.txt") + if not os.path.exists(test_times_file): + test_times_file = os.path.join(suite.source_root, ".lit_test_times.txt") + if os.path.exists(test_times_file): + with open(test_times_file, "r") as time_file: + for line in time_file: + time, path = line.split(maxsplit=1) + test_times[path.strip("\n")] = float(time) + return test_times + + +def record_test_times(tests, lit_config): + times_by_suite = {} + for t in tests: + assert t.suite.test_times is None + if t.result.elapsed is None: + continue + if not t.suite.exec_root in times_by_suite: + times_by_suite[t.suite.exec_root] = read_test_times(t.suite) + time = -t.result.elapsed if t.isFailure() else t.result.elapsed + # The "path" here is only used as a key into a dictionary. It is never + # used as an actual path to a filesystem API, therefore we use '/' as + # the canonical separator so that Unix and Windows machines can share + # timing data. + times_by_suite[t.suite.exec_root]["/".join(t.path_in_suite)] = time + + for s, value in times_by_suite.items(): + try: + path = os.path.join(s, ".lit_test_times.txt") + with open(path, "w") as time_file: + for name, time in value.items(): + time_file.write(("%e" % time) + " " + name + "\n") + except: + lit_config.warning("Could not save test time: " + path) + continue diff --git a/wemm/lib/python3.10/site-packages/lit/TestingConfig.py b/wemm/lib/python3.10/site-packages/lit/TestingConfig.py new file mode 100644 index 0000000000000000000000000000000000000000..eb9f8de2a7f960ceacf550dce61b238a370679d1 --- /dev/null +++ b/wemm/lib/python3.10/site-packages/lit/TestingConfig.py @@ -0,0 +1,267 @@ +import os +import sys + + +class TestingConfig(object): + """ + TestingConfig - Information on the tests inside a suite. + """ + + @staticmethod + def fromdefaults(litConfig): + """ + fromdefaults(litConfig) -> TestingConfig + + Create a TestingConfig object with default values. + """ + # Set the environment based on the command line arguments. + environment = { + "PATH": os.pathsep.join(litConfig.path + [os.environ.get("PATH", "")]), + "LLVM_DISABLE_CRASH_REPORT": "1", + } + + pass_vars = [ + "LIBRARY_PATH", + "LD_LIBRARY_PATH", + "SYSTEMROOT", + "TERM", + "CLANG", + "LLDB", + "LD_PRELOAD", + "LLVM_SYMBOLIZER_PATH", + "LLVM_PROFILE_FILE", + "ASAN_SYMBOLIZER_PATH", + "HWASAN_SYMBOLIZER_PATH", + "LSAN_SYMBOLIZER_PATH", + "MSAN_SYMBOLIZER_PATH", + "TSAN_SYMBOLIZER_PATH", + "UBSAN_SYMBOLIZER_PATH", + "ASAN_OPTIONS", + "LSAN_OPTIONS", + "HWASAN_OPTIONS", + "MSAN_OPTIONS", + "TSAN_OPTIONS", + "UBSAN_OPTIONS", + "ADB", + "ADB_SERVER_SOCKET", + "ANDROID_SERIAL", + "SSH_AUTH_SOCK", + "SANITIZER_IGNORE_CVE_2016_2143", + "TMPDIR", + "TMP", + "TEMP", + "TEMPDIR", + "AVRLIT_BOARD", + "AVRLIT_PORT", + "FILECHECK_OPTS", + "VCINSTALLDIR", + "VCToolsinstallDir", + "VSINSTALLDIR", + "WindowsSdkDir", + "WindowsSDKLibVersion", + "SOURCE_DATE_EPOCH", + "GTEST_FILTER", + "DFLTCC", + ] + + if sys.platform.startswith("aix"): + pass_vars += ["LIBPATH"] + elif sys.platform == "win32": + pass_vars += [ + "COMSPEC", + "INCLUDE", + "LIB", + "PATHEXT", + "USERPROFILE", + ] + environment["PYTHONBUFFERED"] = "1" + # Avoid Windows heuristics which try to detect potential installer + # programs (which may need to run with elevated privileges) and ask + # if the user wants to run them in that way. This heuristic may + # match for executables containing the substrings "patch" (which is + # a substring of "dispatch"), "update", "setup", etc. Set this + # environment variable indicating that we want to execute them with + # the current user. + environment["__COMPAT_LAYER"] = "RunAsInvoker" + + for var in pass_vars: + val = os.environ.get(var, "") + # Check for empty string as some variables such as LD_PRELOAD cannot be empty + # ('') for OS's such as OpenBSD. + if val: + environment[var] = val + + # Set the default available features based on the LitConfig. + available_features = [] + if litConfig.useValgrind: + available_features.append("valgrind") + if litConfig.valgrindLeakCheck: + available_features.append("vg_leak") + + return TestingConfig( + None, + name="", + suffixes=set(), + test_format=None, + environment=environment, + substitutions=[], + unsupported=False, + test_exec_root=None, + test_source_root=None, + excludes=[], + available_features=available_features, + pipefail=True, + standalone_tests=False, + ) + + def load_from_path(self, path, litConfig): + """ + load_from_path(path, litConfig) + + Load the configuration module at the provided path into the given config + object. + """ + + # Load the config script data. + data = None + f = open(path) + try: + data = f.read() + except: + litConfig.fatal("unable to load config file: %r" % (path,)) + f.close() + + # Execute the config script to initialize the object. + cfg_globals = dict(globals()) + cfg_globals["config"] = self + cfg_globals["lit_config"] = litConfig + cfg_globals["__file__"] = path + try: + exec(compile(data, path, "exec"), cfg_globals, None) + if litConfig.debug: + litConfig.note("... loaded config %r" % path) + except SystemExit: + e = sys.exc_info()[1] + # We allow normal system exit inside a config file to just + # return control without error. + if e.args: + raise + except: + import traceback + + litConfig.fatal( + "unable to parse config file %r, traceback: %s" + % (path, traceback.format_exc()) + ) + self.finish(litConfig) + + def __init__( + self, + parent, + name, + suffixes, + test_format, + environment, + substitutions, + unsupported, + test_exec_root, + test_source_root, + excludes, + available_features, + pipefail, + limit_to_features=[], + is_early=False, + parallelism_group=None, + standalone_tests=False, + ): + self.parent = parent + self.name = str(name) + self.suffixes = set(suffixes) + self.test_format = test_format + self.environment = dict(environment) + self.substitutions = list(substitutions) + self.unsupported = unsupported + self.test_exec_root = test_exec_root + self.test_source_root = test_source_root + self.excludes = set(excludes) + self.available_features = set(available_features) + self.pipefail = pipefail + self.standalone_tests = standalone_tests + # This list is used by TestRunner.py to restrict running only tests that + # require one of the features in this list if this list is non-empty. + # Configurations can set this list to restrict the set of tests to run. + self.limit_to_features = set(limit_to_features) + self.parallelism_group = parallelism_group + self._recursiveExpansionLimit = None + + @property + def recursiveExpansionLimit(self): + return self._recursiveExpansionLimit + + @recursiveExpansionLimit.setter + def recursiveExpansionLimit(self, value): + if value is not None and not isinstance(value, int): + raise ValueError( + "recursiveExpansionLimit must be either None or an integer (got <{}>)".format( + value + ) + ) + if isinstance(value, int) and value < 0: + raise ValueError( + "recursiveExpansionLimit must be a non-negative integer (got <{}>)".format( + value + ) + ) + self._recursiveExpansionLimit = value + + def finish(self, litConfig): + """finish() - Finish this config object, after loading is complete.""" + + self.name = str(self.name) + self.suffixes = set(self.suffixes) + self.environment = dict(self.environment) + self.substitutions = list(self.substitutions) + if self.test_exec_root is not None: + # FIXME: This should really only be suite in test suite config + # files. Should we distinguish them? + self.test_exec_root = str(self.test_exec_root) + if self.test_source_root is not None: + # FIXME: This should really only be suite in test suite config + # files. Should we distinguish them? + self.test_source_root = str(self.test_source_root) + self.excludes = set(self.excludes) + + @property + def root(self): + """root attribute - The root configuration for the test suite.""" + if self.parent is None: + return self + else: + return self.parent.root + + +class SubstituteCaptures: + """ + Helper class to indicate that the substitutions contains backreferences. + + This can be used as the following in lit.cfg to mark subsitutions as having + back-references:: + + config.substutions.append(('\b[^ ]*.cpp', SubstituteCaptures('\0.txt'))) + + """ + + def __init__(self, substitution): + self.substitution = substitution + + def replace(self, pattern, replacement): + return self.substitution + + def __str__(self): + return self.substitution + + def __len__(self): + return len(self.substitution) + + def __getitem__(self, item): + return self.substitution.__getitem__(item) diff --git a/wemm/lib/python3.10/site-packages/lit/__init__.py b/wemm/lib/python3.10/site-packages/lit/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e5a3f79c6843ab60a619526840eb62c902cb4788 --- /dev/null +++ b/wemm/lib/python3.10/site-packages/lit/__init__.py @@ -0,0 +1,8 @@ +"""'lit' Testing Tool""" + +__author__ = "Daniel Dunbar" +__email__ = "daniel@minormatter.com" +__versioninfo__ = (18, 1, 8) +__version__ = ".".join(str(v) for v in __versioninfo__) + +__all__ = [] diff --git a/wemm/lib/python3.10/site-packages/lit/builtin_commands/__init__.py b/wemm/lib/python3.10/site-packages/lit/builtin_commands/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/wemm/lib/python3.10/site-packages/lit/builtin_commands/__pycache__/__init__.cpython-310.pyc b/wemm/lib/python3.10/site-packages/lit/builtin_commands/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8c76ffd43f121ad7e82982758a01d669f02e6d96 Binary files /dev/null and b/wemm/lib/python3.10/site-packages/lit/builtin_commands/__pycache__/__init__.cpython-310.pyc differ diff --git a/wemm/lib/python3.10/site-packages/lit/builtin_commands/__pycache__/cat.cpython-310.pyc b/wemm/lib/python3.10/site-packages/lit/builtin_commands/__pycache__/cat.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4155aa280a1782d5d062a05a9e59cd3188a72da4 Binary files /dev/null and b/wemm/lib/python3.10/site-packages/lit/builtin_commands/__pycache__/cat.cpython-310.pyc differ diff --git a/wemm/lib/python3.10/site-packages/lit/builtin_commands/cat.py b/wemm/lib/python3.10/site-packages/lit/builtin_commands/cat.py new file mode 100644 index 0000000000000000000000000000000000000000..37f55c0aef210b82398c5f07248e44555ec58b31 --- /dev/null +++ b/wemm/lib/python3.10/site-packages/lit/builtin_commands/cat.py @@ -0,0 +1,71 @@ +import getopt +import sys + +try: + from StringIO import StringIO +except ImportError: + from io import StringIO + + +def convertToCaretAndMNotation(data): + newdata = StringIO() + if isinstance(data, str): + data = bytearray(data) + + for intval in data: + if intval == 9 or intval == 10: + newdata.write(chr(intval)) + continue + if intval > 127: + intval = intval - 128 + newdata.write("M-") + if intval < 32: + newdata.write("^") + newdata.write(chr(intval + 64)) + elif intval == 127: + newdata.write("^?") + else: + newdata.write(chr(intval)) + + return newdata.getvalue().encode() + + +def main(argv): + arguments = argv[1:] + short_options = "v" + long_options = ["show-nonprinting"] + show_nonprinting = False + + try: + options, filenames = getopt.gnu_getopt(arguments, short_options, long_options) + except getopt.GetoptError as err: + sys.stderr.write("Unsupported: 'cat': %s\n" % str(err)) + sys.exit(1) + + for option, value in options: + if option == "-v" or option == "--show-nonprinting": + show_nonprinting = True + + writer = getattr(sys.stdout, "buffer", None) + if writer is None: + writer = sys.stdout + if sys.platform == "win32": + import os, msvcrt + + msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY) + for filename in filenames: + try: + fileToCat = open(filename, "rb") + contents = fileToCat.read() + if show_nonprinting: + contents = convertToCaretAndMNotation(contents) + writer.write(contents) + sys.stdout.flush() + fileToCat.close() + except IOError as error: + sys.stderr.write(str(error)) + sys.exit(1) + + +if __name__ == "__main__": + main(sys.argv) diff --git a/wemm/lib/python3.10/site-packages/lit/builtin_commands/diff.py b/wemm/lib/python3.10/site-packages/lit/builtin_commands/diff.py new file mode 100644 index 0000000000000000000000000000000000000000..fbf4eb0e137b34c18fe96099bf88e7c9abfb634d --- /dev/null +++ b/wemm/lib/python3.10/site-packages/lit/builtin_commands/diff.py @@ -0,0 +1,307 @@ +import difflib +import functools +import getopt +import io +import locale +import os +import re +import sys + +import util +from util import to_string + + +class DiffFlags: + def __init__(self): + self.ignore_all_space = False + self.ignore_space_change = False + self.ignore_matching_lines = False + self.ignore_matching_lines_regex = "" + self.unified_diff = False + self.num_context_lines = 3 + self.recursive_diff = False + self.strip_trailing_cr = False + + +def getDirTree(path, basedir=""): + # Tree is a tuple of form (dirname, child_trees). + # An empty dir has child_trees = [], a file has child_trees = None. + child_trees = [] + for dirname, child_dirs, files in os.walk(os.path.join(basedir, path)): + for child_dir in child_dirs: + child_trees.append(getDirTree(child_dir, dirname)) + for filename in files: + child_trees.append((filename, None)) + return path, sorted(child_trees) + + +def compareTwoFiles(flags, filepaths): + filelines = [] + for file in filepaths: + if file == "-": + stdin_fileno = sys.stdin.fileno() + with os.fdopen(os.dup(stdin_fileno), "rb") as stdin_bin: + filelines.append(stdin_bin.readlines()) + else: + with open(file, "rb") as file_bin: + filelines.append(file_bin.readlines()) + + try: + return compareTwoTextFiles( + flags, filepaths, filelines, locale.getpreferredencoding(False) + ) + except UnicodeDecodeError: + try: + return compareTwoTextFiles(flags, filepaths, filelines, "utf-8") + except: + return compareTwoBinaryFiles(flags, filepaths, filelines) + + +def compareTwoBinaryFiles(flags, filepaths, filelines): + exitCode = 0 + if hasattr(difflib, "diff_bytes"): + # python 3.5 or newer + diffs = difflib.diff_bytes( + difflib.unified_diff, + filelines[0], + filelines[1], + filepaths[0].encode(), + filepaths[1].encode(), + n=flags.num_context_lines, + ) + diffs = [diff.decode(errors="backslashreplace") for diff in diffs] + else: + # python 2.7 + if flags.unified_diff: + func = difflib.unified_diff + else: + func = difflib.context_diff + diffs = func( + filelines[0], + filelines[1], + filepaths[0], + filepaths[1], + n=flags.num_context_lines, + ) + + for diff in diffs: + sys.stdout.write(to_string(diff)) + exitCode = 1 + return exitCode + + +def compareTwoTextFiles(flags, filepaths, filelines_bin, encoding): + filelines = [] + for lines_bin in filelines_bin: + lines = [] + for line_bin in lines_bin: + line = line_bin.decode(encoding=encoding) + lines.append(line) + filelines.append(lines) + + exitCode = 0 + + def compose2(f, g): + return lambda x: f(g(x)) + + f = lambda x: x + if flags.strip_trailing_cr: + f = compose2(lambda line: line.replace("\r\n", "\n"), f) + if flags.ignore_all_space or flags.ignore_space_change: + ignoreSpace = lambda line, separator: separator.join(line.split()) + "\n" + ignoreAllSpaceOrSpaceChange = functools.partial( + ignoreSpace, separator="" if flags.ignore_all_space else " " + ) + f = compose2(ignoreAllSpaceOrSpaceChange, f) + + for idx, lines in enumerate(filelines): + if flags.ignore_matching_lines: + lines = filter( + lambda x: not re.match( + r"{}".format(flags.ignore_matching_lines_regex), x + ), + lines, + ) + filelines[idx] = [f(line) for line in lines] + + func = difflib.unified_diff if flags.unified_diff else difflib.context_diff + for diff in func( + filelines[0], + filelines[1], + filepaths[0], + filepaths[1], + n=flags.num_context_lines, + ): + sys.stdout.write(to_string(diff)) + exitCode = 1 + return exitCode + + +def printDirVsFile(dir_path, file_path): + if os.path.getsize(file_path): + msg = "File %s is a directory while file %s is a regular file" + else: + msg = "File %s is a directory while file %s is a regular empty file" + sys.stdout.write(msg % (dir_path, file_path) + "\n") + + +def printFileVsDir(file_path, dir_path): + if os.path.getsize(file_path): + msg = "File %s is a regular file while file %s is a directory" + else: + msg = "File %s is a regular empty file while file %s is a directory" + sys.stdout.write(msg % (file_path, dir_path) + "\n") + + +def printOnlyIn(basedir, path, name): + sys.stdout.write("Only in %s: %s\n" % (os.path.join(basedir, path), name)) + + +def compareDirTrees(flags, dir_trees, base_paths=["", ""]): + # Dirnames of the trees are not checked, it's caller's responsibility, + # as top-level dirnames are always different. Base paths are important + # for doing os.walk, but we don't put it into tree's dirname in order + # to speed up string comparison below and while sorting in getDirTree. + left_tree, right_tree = dir_trees[0], dir_trees[1] + left_base, right_base = base_paths[0], base_paths[1] + + # Compare two files or report file vs. directory mismatch. + if left_tree[1] is None and right_tree[1] is None: + return compareTwoFiles( + flags, + [ + os.path.join(left_base, left_tree[0]), + os.path.join(right_base, right_tree[0]), + ], + ) + + if left_tree[1] is None and right_tree[1] is not None: + printFileVsDir( + os.path.join(left_base, left_tree[0]), + os.path.join(right_base, right_tree[0]), + ) + return 1 + + if left_tree[1] is not None and right_tree[1] is None: + printDirVsFile( + os.path.join(left_base, left_tree[0]), + os.path.join(right_base, right_tree[0]), + ) + return 1 + + # Compare two directories via recursive use of compareDirTrees. + exitCode = 0 + left_names = [node[0] for node in left_tree[1]] + right_names = [node[0] for node in right_tree[1]] + l, r = 0, 0 + while l < len(left_names) and r < len(right_names): + # Names are sorted in getDirTree, rely on that order. + if left_names[l] < right_names[r]: + exitCode = 1 + printOnlyIn(left_base, left_tree[0], left_names[l]) + l += 1 + elif left_names[l] > right_names[r]: + exitCode = 1 + printOnlyIn(right_base, right_tree[0], right_names[r]) + r += 1 + else: + exitCode |= compareDirTrees( + flags, + [left_tree[1][l], right_tree[1][r]], + [ + os.path.join(left_base, left_tree[0]), + os.path.join(right_base, right_tree[0]), + ], + ) + l += 1 + r += 1 + + # At least one of the trees has ended. Report names from the other tree. + while l < len(left_names): + exitCode = 1 + printOnlyIn(left_base, left_tree[0], left_names[l]) + l += 1 + while r < len(right_names): + exitCode = 1 + printOnlyIn(right_base, right_tree[0], right_names[r]) + r += 1 + return exitCode + + +def main(argv): + if sys.platform == "win32": + if hasattr(sys.stdout, "buffer"): + # python 3 + sys.stdout = io.TextIOWrapper(sys.stdout.buffer, newline="\n") + else: + # python 2.7 + import msvcrt + + msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY) + args = argv[1:] + try: + opts, args = getopt.gnu_getopt(args, "wbuI:U:r", ["strip-trailing-cr"]) + except getopt.GetoptError as err: + sys.stderr.write("Unsupported: 'diff': %s\n" % str(err)) + sys.exit(1) + + flags = DiffFlags() + filelines, filepaths, dir_trees = ([] for i in range(3)) + for o, a in opts: + if o == "-w": + flags.ignore_all_space = True + elif o == "-b": + flags.ignore_space_change = True + elif o == "-u": + flags.unified_diff = True + elif o.startswith("-U"): + flags.unified_diff = True + try: + flags.num_context_lines = int(a) + if flags.num_context_lines < 0: + raise ValueException + except: + sys.stderr.write("Error: invalid '-U' argument: {}\n".format(a)) + sys.exit(1) + elif o == "-I": + flags.ignore_matching_lines = True + flags.ignore_matching_lines_regex = a + elif o == "-r": + flags.recursive_diff = True + elif o == "--strip-trailing-cr": + flags.strip_trailing_cr = True + else: + assert False, "unhandled option" + + if len(args) != 2: + sys.stderr.write("Error: missing or extra operand\n") + sys.exit(1) + + exitCode = 0 + try: + for file in args: + if file != "-" and not os.path.isabs(file): + file = util.abs_path_preserve_drive(file) + + if flags.recursive_diff: + if file == "-": + sys.stderr.write("Error: cannot recursively compare '-'\n") + sys.exit(1) + dir_trees.append(getDirTree(file)) + else: + filepaths.append(file) + + if not flags.recursive_diff: + exitCode = compareTwoFiles(flags, filepaths) + else: + exitCode = compareDirTrees(flags, dir_trees) + + except IOError as err: + sys.stderr.write("Error: 'diff' command failed, %s\n" % str(err)) + exitCode = 1 + + sys.exit(exitCode) + + +if __name__ == "__main__": + main(sys.argv) diff --git a/wemm/lib/python3.10/site-packages/lit/cl_arguments.py b/wemm/lib/python3.10/site-packages/lit/cl_arguments.py new file mode 100644 index 0000000000000000000000000000000000000000..b9122d07afd8a102260ac960936701d45ddc9c9d --- /dev/null +++ b/wemm/lib/python3.10/site-packages/lit/cl_arguments.py @@ -0,0 +1,376 @@ +import argparse +import enum +import os +import shlex +import sys + +import lit.reports +import lit.util + + +@enum.unique +class TestOrder(enum.Enum): + LEXICAL = "lexical" + RANDOM = "random" + SMART = "smart" + + +def parse_args(): + parser = argparse.ArgumentParser(prog="lit", fromfile_prefix_chars="@") + parser.add_argument( + "test_paths", + nargs="+", + metavar="TEST_PATH", + help="File or path to include in the test suite", + ) + + parser.add_argument( + "--version", action="version", version="%(prog)s " + lit.__version__ + ) + + parser.add_argument( + "-j", + "--threads", + "--workers", + dest="workers", + metavar="N", + help="Number of workers used for testing", + type=_positive_int, + default=os.getenv("LIT_MAX_WORKERS", lit.util.usable_core_count()), + ) + parser.add_argument( + "--config-prefix", + dest="configPrefix", + metavar="NAME", + help="Prefix for 'lit' config files", + ) + parser.add_argument( + "-D", + "--param", + dest="user_params", + metavar="NAME=VAL", + help="Add 'NAME' = 'VAL' to the user defined parameters", + action="append", + default=[], + ) + + format_group = parser.add_argument_group("Output Format") + # FIXME: I find these names very confusing, although I like the + # functionality. + format_group.add_argument( + "-q", "--quiet", help="Suppress no error output", action="store_true" + ) + format_group.add_argument( + "-s", + "--succinct", + help="Reduce amount of output." + " Additionally, show a progress bar," + " unless --no-progress-bar is specified.", + action="store_true", + ) + format_group.add_argument( + "-v", + "--verbose", + dest="showOutput", + help="For failed tests, show all output. For example, each command is" + " printed before it is executed, so the last printed command is the one" + " that failed.", + action="store_true", + ) + format_group.add_argument( + "-vv", + "--echo-all-commands", + dest="showOutput", + help="Deprecated alias for -v.", + action="store_true", + ) + format_group.add_argument( + "-a", + "--show-all", + dest="showAllOutput", + help="Enable -v, but for all tests not just failed tests.", + action="store_true", + ) + format_group.add_argument( + "-o", + "--output", + type=lit.reports.JsonReport, + help="Write test results to the provided path", + metavar="PATH", + ) + format_group.add_argument( + "--no-progress-bar", + dest="useProgressBar", + help="Do not use curses based progress bar", + action="store_false", + ) + + # Note: this does not generate flags for user-defined result codes. + success_codes = [c for c in lit.Test.ResultCode.all_codes() if not c.isFailure] + for code in success_codes: + format_group.add_argument( + "--show-{}".format(code.name.lower()), + dest="shown_codes", + help="Show {} tests ({})".format(code.label.lower(), code.name), + action="append_const", + const=code, + default=[], + ) + + execution_group = parser.add_argument_group("Test Execution") + execution_group.add_argument( + "--gtest-sharding", + help="Enable sharding for GoogleTest format", + action="store_true", + default=True, + ) + execution_group.add_argument( + "--no-gtest-sharding", + dest="gtest_sharding", + help="Disable sharding for GoogleTest format", + action="store_false", + ) + execution_group.add_argument( + "--path", + help="Additional paths to add to testing environment", + action="append", + default=[], + type=os.path.abspath, + ) + execution_group.add_argument( + "--vg", dest="useValgrind", help="Run tests under valgrind", action="store_true" + ) + execution_group.add_argument( + "--vg-leak", + dest="valgrindLeakCheck", + help="Check for memory leaks under valgrind", + action="store_true", + ) + execution_group.add_argument( + "--vg-arg", + dest="valgrindArgs", + metavar="ARG", + help="Specify an extra argument for valgrind", + action="append", + default=[], + ) + execution_group.add_argument( + "--time-tests", + help="Track elapsed wall time for each test", + action="store_true", + ) + execution_group.add_argument( + "--no-execute", + dest="noExecute", + help="Don't execute any tests (assume PASS)", + action="store_true", + ) + execution_group.add_argument( + "--xunit-xml-output", + type=lit.reports.XunitReport, + help="Write XUnit-compatible XML test reports to the specified file", + ) + execution_group.add_argument( + "--resultdb-output", + type=lit.reports.ResultDBReport, + help="Write LuCI ResuldDB compatible JSON to the specified file", + ) + execution_group.add_argument( + "--time-trace-output", + type=lit.reports.TimeTraceReport, + help="Write Chrome tracing compatible JSON to the specified file", + ) + execution_group.add_argument( + "--timeout", + dest="maxIndividualTestTime", + help="Maximum time to spend running a single test (in seconds). " + "0 means no time limit. [Default: 0]", + type=_non_negative_int, + ) + execution_group.add_argument( + "--max-failures", + help="Stop execution after the given number of failures.", + type=_positive_int, + ) + execution_group.add_argument( + "--allow-empty-runs", + help="Do not fail the run if all tests are filtered out", + action="store_true", + ) + execution_group.add_argument( + "--per-test-coverage", + dest="per_test_coverage", + action="store_true", + help="Enable individual test case coverage", + ) + execution_group.add_argument( + "--ignore-fail", + dest="ignoreFail", + action="store_true", + help="Exit with status zero even if some tests fail", + ) + + selection_group = parser.add_argument_group("Test Selection") + selection_group.add_argument( + "--max-tests", + metavar="N", + help="Maximum number of tests to run", + type=_positive_int, + ) + selection_group.add_argument( + "--max-time", + dest="timeout", + metavar="N", + help="Maximum time to spend testing (in seconds)", + type=_positive_int, + ) + selection_group.add_argument( + "--order", + choices=[x.value for x in TestOrder], + default=TestOrder.SMART, + help="Test order to use (default: smart)", + ) + selection_group.add_argument( + "--shuffle", + dest="order", + help="Run tests in random order (DEPRECATED: use --order=random)", + action="store_const", + const=TestOrder.RANDOM, + ) + selection_group.add_argument( + "-i", + "--incremental", + help="Run failed tests first (DEPRECATED: use --order=smart)", + action="store_true", + ) + selection_group.add_argument( + "--filter", + metavar="REGEX", + type=_case_insensitive_regex, + help="Only run tests with paths matching the given regular expression", + default=os.environ.get("LIT_FILTER", ".*"), + ) + selection_group.add_argument( + "--filter-out", + metavar="REGEX", + type=_case_insensitive_regex, + help="Filter out tests with paths matching the given regular expression", + default=os.environ.get("LIT_FILTER_OUT", "^$"), + ) + selection_group.add_argument( + "--xfail", + metavar="LIST", + type=_semicolon_list, + help="XFAIL tests with paths in the semicolon separated list", + default=os.environ.get("LIT_XFAIL", ""), + ) + selection_group.add_argument( + "--xfail-not", + metavar="LIST", + type=_semicolon_list, + help="do not XFAIL tests with paths in the semicolon separated list", + default=os.environ.get("LIT_XFAIL_NOT", ""), + ) + selection_group.add_argument( + "--num-shards", + dest="numShards", + metavar="M", + help="Split testsuite into M pieces and only run one", + type=_positive_int, + default=os.environ.get("LIT_NUM_SHARDS"), + ) + selection_group.add_argument( + "--run-shard", + dest="runShard", + metavar="N", + help="Run shard #N of the testsuite", + type=_positive_int, + default=os.environ.get("LIT_RUN_SHARD"), + ) + + debug_group = parser.add_argument_group("Debug and Experimental Options") + debug_group.add_argument( + "--debug", help="Enable debugging (for 'lit' development)", action="store_true" + ) + debug_group.add_argument( + "--show-suites", + help="Show discovered test suites and exit", + action="store_true", + ) + debug_group.add_argument( + "--show-tests", help="Show all discovered tests and exit", action="store_true" + ) + debug_group.add_argument( + "--show-used-features", + help="Show all features used in the test suite (in XFAIL, UNSUPPORTED and REQUIRES) and exit", + action="store_true", + ) + + # LIT is special: environment variables override command line arguments. + env_args = shlex.split(os.environ.get("LIT_OPTS", "")) + args = sys.argv[1:] + env_args + opts = parser.parse_args(args) + + # Validate command line options + if opts.incremental: + print( + "WARNING: --incremental is deprecated. Failing tests now always run first." + ) + + if opts.numShards or opts.runShard: + if not opts.numShards or not opts.runShard: + parser.error("--num-shards and --run-shard must be used together") + if opts.runShard > opts.numShards: + parser.error("--run-shard must be between 1 and --num-shards (inclusive)") + opts.shard = (opts.runShard, opts.numShards) + else: + opts.shard = None + + opts.reports = filter( + None, + [ + opts.output, + opts.xunit_xml_output, + opts.resultdb_output, + opts.time_trace_output, + ], + ) + + return opts + + +def _positive_int(arg): + return _int(arg, "positive", lambda i: i > 0) + + +def _non_negative_int(arg): + return _int(arg, "non-negative", lambda i: i >= 0) + + +def _int(arg, kind, pred): + desc = "requires {} integer, but found '{}'" + try: + i = int(arg) + except ValueError: + raise _error(desc, kind, arg) + if not pred(i): + raise _error(desc, kind, arg) + return i + + +def _case_insensitive_regex(arg): + import re + + try: + return re.compile(arg, re.IGNORECASE) + except re.error as reason: + raise _error("invalid regular expression: '{}', {}", arg, reason) + + +def _semicolon_list(arg): + return arg.split(";") + + +def _error(desc, *args): + msg = desc.format(*args) + return argparse.ArgumentTypeError(msg) diff --git a/wemm/lib/python3.10/site-packages/lit/discovery.py b/wemm/lib/python3.10/site-packages/lit/discovery.py new file mode 100644 index 0000000000000000000000000000000000000000..2e7f90c6bb0c96051de887e963a5c02c6b0abc25 --- /dev/null +++ b/wemm/lib/python3.10/site-packages/lit/discovery.py @@ -0,0 +1,289 @@ +""" +Test discovery functions. +""" + +import copy +import os +import sys + +from lit.TestingConfig import TestingConfig +from lit import LitConfig, Test, util + + +def chooseConfigFileFromDir(dir, config_names): + for name in config_names: + p = os.path.join(dir, name) + if os.path.exists(p): + return p + return None + + +def dirContainsTestSuite(path, lit_config): + cfgpath = chooseConfigFileFromDir(path, lit_config.site_config_names) + if not cfgpath: + cfgpath = chooseConfigFileFromDir(path, lit_config.config_names) + return cfgpath + + +def getTestSuite(item, litConfig, cache): + """getTestSuite(item, litConfig, cache) -> (suite, relative_path) + + Find the test suite containing @arg item. + + @retval (None, ...) - Indicates no test suite contains @arg item. + @retval (suite, relative_path) - The suite that @arg item is in, and its + relative path inside that suite. + """ + + def search1(path): + # Check for a site config or a lit config. + cfgpath = dirContainsTestSuite(path, litConfig) + + # If we didn't find a config file, keep looking. + if not cfgpath: + parent, base = os.path.split(path) + if parent == path: + return (None, ()) + + ts, relative = search(parent) + return (ts, relative + (base,)) + + # This is a private builtin parameter which can be used to perform + # translation of configuration paths. Specifically, this parameter + # can be set to a dictionary that the discovery process will consult + # when it finds a configuration it is about to load. If the given + # path is in the map, the value of that key is a path to the + # configuration to load instead. + config_map = litConfig.params.get("config_map") + if config_map: + cfgpath = util.abs_path_preserve_drive(cfgpath) + target = config_map.get(os.path.normcase(cfgpath)) + if target: + cfgpath = target + + # We found a test suite, create a new config for it and load it. + if litConfig.debug: + litConfig.note("loading suite config %r" % cfgpath) + + cfg = TestingConfig.fromdefaults(litConfig) + cfg.load_from_path(cfgpath, litConfig) + source_root = util.abs_path_preserve_drive(cfg.test_source_root or path) + exec_root = util.abs_path_preserve_drive(cfg.test_exec_root or path) + return Test.TestSuite(cfg.name, source_root, exec_root, cfg), () + + def search(path): + # Check for an already instantiated test suite. + real_path = util.abs_path_preserve_drive(path) + res = cache.get(real_path) + if res is None: + cache[real_path] = res = search1(path) + return res + + # Canonicalize the path. + item = os.path.normpath(os.path.join(os.getcwd(), item)) + + # Skip files and virtual components. + components = [] + while not os.path.isdir(item): + parent, base = os.path.split(item) + if parent == item: + return (None, ()) + components.append(base) + item = parent + components.reverse() + + ts, relative = search(item) + return ts, tuple(relative + tuple(components)) + + +def getLocalConfig(ts, path_in_suite, litConfig, cache): + def search1(path_in_suite): + # Get the parent config. + if not path_in_suite: + parent = ts.config + else: + parent = search(path_in_suite[:-1]) + + # Check if there is a local configuration file. + source_path = ts.getSourcePath(path_in_suite) + cfgpath = chooseConfigFileFromDir(source_path, litConfig.local_config_names) + + # If not, just reuse the parent config. + if not cfgpath: + return parent + + # Otherwise, copy the current config and load the local configuration + # file into it. + config = copy.deepcopy(parent) + if litConfig.debug: + litConfig.note("loading local config %r" % cfgpath) + config.load_from_path(cfgpath, litConfig) + return config + + def search(path_in_suite): + key = (ts, path_in_suite) + res = cache.get(key) + if res is None: + cache[key] = res = search1(path_in_suite) + return res + + return search(path_in_suite) + + +def getTests(path, litConfig, testSuiteCache, localConfigCache): + # Find the test suite for this input and its relative path. + ts, path_in_suite = getTestSuite(path, litConfig, testSuiteCache) + if ts is None: + litConfig.warning("unable to find test suite for %r" % path) + return (), () + + if litConfig.debug: + litConfig.note("resolved input %r to %r::%r" % (path, ts.name, path_in_suite)) + + return ts, getTestsInSuite( + ts, + path_in_suite, + litConfig, + testSuiteCache, + localConfigCache, + ) + + +def getTestsInSuite( + ts, path_in_suite, litConfig, testSuiteCache, localConfigCache +): + # Check that the source path exists (errors here are reported by the + # caller). + source_path = ts.getSourcePath(path_in_suite) + if not os.path.exists(source_path): + return + + # Check if the user named a test directly. + if not os.path.isdir(source_path): + test_dir_in_suite = path_in_suite[:-1] + lc = getLocalConfig(ts, test_dir_in_suite, litConfig, localConfigCache) + + # If we don't have a test format or if we are running standalone tests, + # always "find" the test itself. Otherwise, we might find no tests at + # all, which is considered an error but isn't an error with standalone + # tests. + tests = [Test.Test(ts, path_in_suite, lc)] if lc.test_format is None or lc.standalone_tests else \ + lc.test_format.getTestsForPath(ts, path_in_suite, litConfig, lc) + + for test in tests: + yield test + return + + # Otherwise we have a directory to search for tests, start by getting the + # local configuration. + lc = getLocalConfig(ts, path_in_suite, litConfig, localConfigCache) + + # Directory contains tests to be run standalone. Do not try to discover. + if lc.standalone_tests: + if lc.suffixes or lc.excludes: + litConfig.warning( + "standalone_tests set in LIT config but suffixes or excludes" + " are also set" + ) + return + + # Search for tests. + if lc.test_format is not None: + for res in lc.test_format.getTestsInDirectory(ts, path_in_suite, litConfig, lc): + yield res + + # Search subdirectories. + for filename in os.listdir(source_path): + # FIXME: This doesn't belong here? + if filename in ("Output", ".svn", ".git") or filename in lc.excludes: + continue + + # Ignore non-directories. + file_sourcepath = os.path.join(source_path, filename) + if not os.path.isdir(file_sourcepath): + continue + + # Check for nested test suites, first in the execpath in case there is a + # site configuration and then in the source path. + subpath = path_in_suite + (filename,) + file_execpath = ts.getExecPath(subpath) + if dirContainsTestSuite(file_execpath, litConfig): + sub_ts, subpath_in_suite = getTestSuite( + file_execpath, litConfig, testSuiteCache + ) + elif dirContainsTestSuite(file_sourcepath, litConfig): + sub_ts, subpath_in_suite = getTestSuite( + file_sourcepath, litConfig, testSuiteCache + ) + else: + sub_ts = None + + # If the this directory recursively maps back to the current test suite, + # disregard it (this can happen if the exec root is located inside the + # current test suite, for example). + if sub_ts is ts: + continue + + # Otherwise, load from the nested test suite, if present. + if sub_ts is not None: + subiter = getTestsInSuite( + sub_ts, + subpath_in_suite, + litConfig, + testSuiteCache, + localConfigCache, + ) + else: + subiter = getTestsInSuite( + ts, + subpath, + litConfig, + testSuiteCache, + localConfigCache, + ) + + N = 0 + for res in subiter: + N += 1 + yield res + if sub_ts and not N: + litConfig.warning("test suite %r contained no tests" % sub_ts.name) + + +def find_tests_for_inputs(lit_config, inputs): + """ + find_tests_for_inputs(lit_config, inputs) -> [Test] + + Given a configuration object and a list of input specifiers, find all the + tests to execute. + """ + + # Load the tests from the inputs. + tests = [] + test_suite_cache = {} + local_config_cache = {} + for input in inputs: + prev = len(tests) + tests.extend( + getTests( + input, + lit_config, + test_suite_cache, + local_config_cache, + )[1] + ) + if prev == len(tests): + lit_config.warning("input %r contained no tests" % input) + + # This data is no longer needed but keeping it around causes awful + # performance problems while the test suites run. + for k, suite in test_suite_cache.items(): + if suite[0]: + suite[0].test_times = None + + # If there were any errors during test discovery, exit now. + if lit_config.numErrors: + sys.stderr.write("%d errors, exiting.\n" % lit_config.numErrors) + sys.exit(2) + + return tests diff --git a/wemm/lib/python3.10/site-packages/lit/display.py b/wemm/lib/python3.10/site-packages/lit/display.py new file mode 100644 index 0000000000000000000000000000000000000000..7de5a298d2302bb5be25cdcb8f4d182b69588755 --- /dev/null +++ b/wemm/lib/python3.10/site-packages/lit/display.py @@ -0,0 +1,169 @@ +import sys + + +def create_display(opts, tests, total_tests, workers): + if opts.quiet: + return NopDisplay() + + num_tests = len(tests) + of_total = (" of %d" % total_tests) if (num_tests != total_tests) else "" + header = "-- Testing: %d%s tests, %d workers --" % (num_tests, of_total, workers) + + progress_bar = None + if opts.succinct and opts.useProgressBar: + import lit.ProgressBar + + try: + tc = lit.ProgressBar.TerminalController() + progress_bar = lit.ProgressBar.ProgressBar(tc, header) + header = None + except ValueError: + progress_bar = lit.ProgressBar.SimpleProgressBar("Testing: ") + + return Display(opts, tests, header, progress_bar) + + +class ProgressPredictor(object): + def __init__(self, tests): + self.completed = 0 + self.time_elapsed = 0.0 + self.predictable_tests_remaining = 0 + self.predictable_time_remaining = 0.0 + self.unpredictable_tests_remaining = 0 + + for test in tests: + if test.previous_elapsed: + self.predictable_tests_remaining += 1 + self.predictable_time_remaining += test.previous_elapsed + else: + self.unpredictable_tests_remaining += 1 + + def update(self, test): + self.completed += 1 + self.time_elapsed += test.result.elapsed + + if test.previous_elapsed: + self.predictable_tests_remaining -= 1 + self.predictable_time_remaining -= test.previous_elapsed + else: + self.unpredictable_tests_remaining -= 1 + + # NOTE: median would be more precise, but might be too slow. + average_test_time = (self.time_elapsed + self.predictable_time_remaining) / ( + self.completed + self.predictable_tests_remaining + ) + unpredictable_time_remaining = ( + average_test_time * self.unpredictable_tests_remaining + ) + total_time_remaining = ( + self.predictable_time_remaining + unpredictable_time_remaining + ) + total_time = self.time_elapsed + total_time_remaining + + if total_time > 0: + return self.time_elapsed / total_time + return 0 + + +class NopDisplay(object): + def print_header(self): + pass + + def update(self, test): + pass + + def clear(self, interrupted): + pass + + +class Display(object): + def __init__(self, opts, tests, header, progress_bar): + self.opts = opts + self.num_tests = len(tests) + self.header = header + self.progress_predictor = ProgressPredictor(tests) if progress_bar else None + self.progress_bar = progress_bar + self.completed = 0 + + def print_header(self): + if self.header: + print(self.header) + if self.progress_bar: + self.progress_bar.update(0.0, "") + + def update(self, test): + self.completed += 1 + + show_result = ( + test.isFailure() + or self.opts.showAllOutput + or (not self.opts.quiet and not self.opts.succinct) + ) + if show_result: + if self.progress_bar: + self.progress_bar.clear(interrupted=False) + self.print_result(test) + + if self.progress_bar: + if test.isFailure(): + self.progress_bar.barColor = "RED" + percent = self.progress_predictor.update(test) + self.progress_bar.update(percent, test.getFullName()) + + def clear(self, interrupted): + if self.progress_bar: + self.progress_bar.clear(interrupted) + + def print_result(self, test): + # Show the test result line. + test_name = test.getFullName() + print( + "%s: %s (%d of %d)" + % (test.result.code.name, test_name, self.completed, self.num_tests) + ) + + # Show the test failure output, if requested. + if (test.isFailure() and self.opts.showOutput) or self.opts.showAllOutput: + if test.isFailure(): + print( + "%s TEST '%s' FAILED %s" % ("*" * 20, test.getFullName(), "*" * 20) + ) + out = test.result.output + # Encode/decode so that, when using Python 3.6.5 in Windows 10, + # print(out) doesn't raise UnicodeEncodeError if out contains + # special characters. However, Python 2 might try to decode + # as part of the encode call if out is already encoded, so skip + # encoding if it raises UnicodeDecodeError. + if sys.stdout.encoding: + try: + out = out.encode(encoding=sys.stdout.encoding, errors="replace") + except UnicodeDecodeError: + pass + # Python 2 can raise UnicodeDecodeError here too in cases + # where the stdout encoding is ASCII. Ignore decode errors + # in this case. + out = out.decode(encoding=sys.stdout.encoding, errors="ignore") + print(out) + print("*" * 20) + + # Report test metrics, if present. + if test.result.metrics: + print("%s TEST '%s' RESULTS %s" % ("*" * 10, test.getFullName(), "*" * 10)) + items = sorted(test.result.metrics.items()) + for metric_name, value in items: + print("%s: %s " % (metric_name, value.format())) + print("*" * 10) + + # Report micro-tests, if present + if test.result.microResults: + items = sorted(test.result.microResults.items()) + for micro_test_name, micro_test in items: + print("%s MICRO-TEST: %s" % ("*" * 3, micro_test_name)) + + if micro_test.metrics: + sorted_metrics = sorted(micro_test.metrics.items()) + for metric_name, value in sorted_metrics: + print(" %s: %s " % (metric_name, value.format())) + + # Ensure the output is flushed. + sys.stdout.flush() diff --git a/wemm/lib/python3.10/site-packages/lit/main.py b/wemm/lib/python3.10/site-packages/lit/main.py new file mode 100644 index 0000000000000000000000000000000000000000..db9f24f748d9e16c609287b2b03e4011f68ddeec --- /dev/null +++ b/wemm/lib/python3.10/site-packages/lit/main.py @@ -0,0 +1,357 @@ +""" +lit - LLVM Integrated Tester. + +See lit.pod for more information. +""" + +import itertools +import os +import platform +import sys +import time + +import lit.cl_arguments +import lit.discovery +import lit.display +import lit.LitConfig +import lit.reports +import lit.run +import lit.Test +import lit.util +from lit.formats.googletest import GoogleTest +from lit.TestTimes import record_test_times + + +def main(builtin_params={}): + opts = lit.cl_arguments.parse_args() + params = create_params(builtin_params, opts.user_params) + is_windows = platform.system() == "Windows" + + lit_config = lit.LitConfig.LitConfig( + progname=os.path.basename(sys.argv[0]), + path=opts.path, + quiet=opts.quiet, + useValgrind=opts.useValgrind, + valgrindLeakCheck=opts.valgrindLeakCheck, + valgrindArgs=opts.valgrindArgs, + noExecute=opts.noExecute, + debug=opts.debug, + isWindows=is_windows, + order=opts.order, + params=params, + config_prefix=opts.configPrefix, + per_test_coverage=opts.per_test_coverage, + gtest_sharding=opts.gtest_sharding, + ) + + discovered_tests = lit.discovery.find_tests_for_inputs( + lit_config, opts.test_paths + ) + if not discovered_tests: + sys.stderr.write("error: did not discover any tests for provided path(s)\n") + sys.exit(2) + + if opts.show_suites or opts.show_tests: + print_discovered(discovered_tests, opts.show_suites, opts.show_tests) + sys.exit(0) + + if opts.show_used_features: + features = set( + itertools.chain.from_iterable( + t.getUsedFeatures() + for t in discovered_tests + if t.gtest_json_file is None + ) + ) + print(" ".join(sorted(features))) + sys.exit(0) + + # Command line overrides configuration for maxIndividualTestTime. + if opts.maxIndividualTestTime is not None: # `not None` is important (default: 0) + if opts.maxIndividualTestTime != lit_config.maxIndividualTestTime: + lit_config.note( + ( + "The test suite configuration requested an individual" + " test timeout of {0} seconds but a timeout of {1} seconds was" + " requested on the command line. Forcing timeout to be {1}" + " seconds." + ).format(lit_config.maxIndividualTestTime, opts.maxIndividualTestTime) + ) + lit_config.maxIndividualTestTime = opts.maxIndividualTestTime + + determine_order(discovered_tests, opts.order) + + selected_tests = [ + t + for t in discovered_tests + if opts.filter.search(t.getFullName()) + and not opts.filter_out.search(t.getFullName()) + ] + + if not selected_tests: + sys.stderr.write( + "error: filter did not match any tests " + "(of %d discovered). " % len(discovered_tests) + ) + if opts.allow_empty_runs: + sys.stderr.write( + "Suppressing error because '--allow-empty-runs' " "was specified.\n" + ) + sys.exit(0) + else: + sys.stderr.write("Use '--allow-empty-runs' to suppress this " "error.\n") + sys.exit(2) + + # When running multiple shards, don't include skipped tests in the xunit + # output since merging the files will result in duplicates. + if opts.shard: + (run, shards) = opts.shard + selected_tests = filter_by_shard(selected_tests, run, shards, lit_config) + if not selected_tests: + sys.stderr.write( + "warning: shard does not contain any tests. " + "Consider decreasing the number of shards.\n" + ) + sys.exit(0) + + selected_tests = selected_tests[: opts.max_tests] + + mark_xfail(discovered_tests, opts) + + mark_excluded(discovered_tests, selected_tests) + + start = time.time() + run_tests(selected_tests, lit_config, opts, len(discovered_tests)) + elapsed = time.time() - start + + record_test_times(selected_tests, lit_config) + + selected_tests, discovered_tests = GoogleTest.post_process_shard_results( + selected_tests, discovered_tests + ) + + if opts.time_tests: + print_histogram(discovered_tests) + + print_results(discovered_tests, elapsed, opts) + + tests_for_report = selected_tests if opts.shard else discovered_tests + for report in opts.reports: + report.write_results(tests_for_report, elapsed) + + if lit_config.numErrors: + sys.stderr.write("\n%d error(s) in tests\n" % lit_config.numErrors) + sys.exit(2) + + if lit_config.numWarnings: + sys.stderr.write("\n%d warning(s) in tests\n" % lit_config.numWarnings) + + has_failure = any(t.isFailure() for t in discovered_tests) + if has_failure: + if opts.ignoreFail: + sys.stderr.write( + "\nExiting with status 0 instead of 1 because " + "'--ignore-fail' was specified.\n" + ) + else: + sys.exit(1) + + +def create_params(builtin_params, user_params): + def parse(p): + return p.split("=", 1) if "=" in p else (p, "") + + params = dict(builtin_params) + params.update([parse(p) for p in user_params]) + return params + + +def print_discovered(tests, show_suites, show_tests): + tests.sort(key=lit.reports.by_suite_and_test_path) + + if show_suites: + tests_by_suite = itertools.groupby(tests, lambda t: t.suite) + print("-- Test Suites --") + for suite, test_iter in tests_by_suite: + test_count = sum(1 for _ in test_iter) + print(" %s - %d tests" % (suite.name, test_count)) + print(" Source Root: %s" % suite.source_root) + print(" Exec Root : %s" % suite.exec_root) + features = " ".join(sorted(suite.config.available_features)) + print(" Available Features: %s" % features) + substitutions = sorted(suite.config.substitutions) + substitutions = ("%s => %s" % (x, y) for (x, y) in substitutions) + substitutions = "\n".ljust(30).join(substitutions) + print(" Available Substitutions: %s" % substitutions) + + if show_tests: + print("-- Available Tests --") + for t in tests: + print(" %s" % t.getFullName()) + + +def determine_order(tests, order): + from lit.cl_arguments import TestOrder + + enum_order = TestOrder(order) + if enum_order == TestOrder.RANDOM: + import random + + random.shuffle(tests) + elif enum_order == TestOrder.LEXICAL: + tests.sort(key=lambda t: t.getFullName()) + else: + assert enum_order == TestOrder.SMART, "Unknown TestOrder value" + tests.sort( + key=lambda t: (not t.previous_failure, -t.previous_elapsed, t.getFullName()) + ) + + +def filter_by_shard(tests, run, shards, lit_config): + test_ixs = range(run - 1, len(tests), shards) + selected_tests = [tests[i] for i in test_ixs] + + # For clarity, generate a preview of the first few test indices in the shard + # to accompany the arithmetic expression. + preview_len = 3 + preview = ", ".join([str(i + 1) for i in test_ixs[:preview_len]]) + if len(test_ixs) > preview_len: + preview += ", ..." + msg = ( + f"Selecting shard {run}/{shards} = " + f"size {len(selected_tests)}/{len(tests)} = " + f"tests #({shards}*k)+{run} = [{preview}]" + ) + lit_config.note(msg) + return selected_tests + + +def mark_xfail(selected_tests, opts): + for t in selected_tests: + test_file = os.sep.join(t.path_in_suite) + test_full_name = t.getFullName() + if test_file in opts.xfail or test_full_name in opts.xfail: + t.xfails += "*" + if test_file in opts.xfail_not or test_full_name in opts.xfail_not: + t.xfail_not = True + + +def mark_excluded(discovered_tests, selected_tests): + excluded_tests = set(discovered_tests) - set(selected_tests) + result = lit.Test.Result(lit.Test.EXCLUDED) + for t in excluded_tests: + t.setResult(result) + + +def run_tests(tests, lit_config, opts, discovered_tests): + workers = min(len(tests), opts.workers) + display = lit.display.create_display(opts, tests, discovered_tests, workers) + + run = lit.run.Run( + tests, lit_config, workers, display.update, opts.max_failures, opts.timeout + ) + + display.print_header() + + interrupted = False + error = None + try: + execute_in_tmp_dir(run, lit_config) + except KeyboardInterrupt: + interrupted = True + error = " interrupted by user" + except lit.run.MaxFailuresError: + error = "warning: reached maximum number of test failures" + except lit.run.TimeoutError: + error = "warning: reached timeout" + + display.clear(interrupted) + if error: + sys.stderr.write("%s, skipping remaining tests\n" % error) + + +def execute_in_tmp_dir(run, lit_config): + # Create a temp directory inside the normal temp directory so that we can + # try to avoid temporary test file leaks. The user can avoid this behavior + # by setting LIT_PRESERVES_TMP in the environment, so they can easily use + # their own temp directory to monitor temporary file leaks or handle them at + # the buildbot level. + tmp_dir = None + if "LIT_PRESERVES_TMP" not in os.environ: + import tempfile + + # z/OS linker does not support '_' in paths, so use '-'. + tmp_dir = tempfile.mkdtemp(prefix="lit-tmp-") + tmp_dir_envs = {k: tmp_dir for k in ["TMP", "TMPDIR", "TEMP", "TEMPDIR"]} + os.environ.update(tmp_dir_envs) + for cfg in {t.config for t in run.tests}: + cfg.environment.update(tmp_dir_envs) + try: + run.execute() + finally: + if tmp_dir: + try: + import shutil + + shutil.rmtree(tmp_dir) + except Exception as e: + lit_config.warning( + "Failed to delete temp directory '%s', try upgrading your version of Python to fix this" + % tmp_dir + ) + + +def print_histogram(tests): + test_times = [ + (t.getFullName(), t.result.elapsed) for t in tests if t.result.elapsed + ] + if test_times: + lit.util.printHistogram(test_times, title="Tests") + + +def print_results(tests, elapsed, opts): + tests_by_code = {code: [] for code in lit.Test.ResultCode.all_codes()} + total_tests = len(tests) + for test in tests: + tests_by_code[test.result.code].append(test) + + for code in lit.Test.ResultCode.all_codes(): + print_group( + sorted(tests_by_code[code], key=lambda t: t.getFullName()), + code, + opts.shown_codes, + ) + + print_summary(total_tests, tests_by_code, opts.quiet, elapsed) + + +def print_group(tests, code, shown_codes): + if not tests: + return + if not code.isFailure and code not in shown_codes: + return + print("*" * 20) + print("{} Tests ({}):".format(code.label, len(tests))) + for test in tests: + print(" %s" % test.getFullName()) + sys.stdout.write("\n") + + +def print_summary(total_tests, tests_by_code, quiet, elapsed): + if not quiet: + print("\nTesting Time: %.2fs" % elapsed) + + print("\nTotal Discovered Tests: %s" % (total_tests)) + codes = [c for c in lit.Test.ResultCode.all_codes() if not quiet or c.isFailure] + groups = [(c.label, len(tests_by_code[c])) for c in codes] + groups = [(label, count) for label, count in groups if count] + if not groups: + return + + max_label_len = max(len(label) for label, _ in groups) + max_count_len = max(len(str(count)) for _, count in groups) + + for (label, count) in groups: + label = label.ljust(max_label_len) + count = str(count).rjust(max_count_len) + print(" %s: %s (%.2f%%)" % (label, count, float(count) / total_tests * 100)) diff --git a/wemm/lib/python3.10/site-packages/lit/reports.py b/wemm/lib/python3.10/site-packages/lit/reports.py new file mode 100644 index 0000000000000000000000000000000000000000..2ac44b0c0ce86e81e48be9b2ef7b60cfe3932a70 --- /dev/null +++ b/wemm/lib/python3.10/site-packages/lit/reports.py @@ -0,0 +1,280 @@ +import base64 +import datetime +import itertools +import json + +from xml.sax.saxutils import quoteattr as quo + +import lit.Test + + +def by_suite_and_test_path(test): + # Suite names are not necessarily unique. Include object identity in sort + # key to avoid mixing tests of different suites. + return (test.suite.name, id(test.suite), test.path_in_suite) + + +class JsonReport(object): + def __init__(self, output_file): + self.output_file = output_file + + def write_results(self, tests, elapsed): + unexecuted_codes = {lit.Test.EXCLUDED, lit.Test.SKIPPED} + tests = [t for t in tests if t.result.code not in unexecuted_codes] + # Construct the data we will write. + data = {} + # Encode the current lit version as a schema version. + data["__version__"] = lit.__versioninfo__ + data["elapsed"] = elapsed + # FIXME: Record some information on the lit configuration used? + # FIXME: Record information from the individual test suites? + + # Encode the tests. + data["tests"] = tests_data = [] + for test in tests: + test_data = { + "name": test.getFullName(), + "code": test.result.code.name, + "output": test.result.output, + "elapsed": test.result.elapsed, + } + + # Add test metrics, if present. + if test.result.metrics: + test_data["metrics"] = metrics_data = {} + for key, value in test.result.metrics.items(): + metrics_data[key] = value.todata() + + # Report micro-tests separately, if present + if test.result.microResults: + for key, micro_test in test.result.microResults.items(): + # Expand parent test name with micro test name + parent_name = test.getFullName() + micro_full_name = parent_name + ":" + key + + micro_test_data = { + "name": micro_full_name, + "code": micro_test.code.name, + "output": micro_test.output, + "elapsed": micro_test.elapsed, + } + if micro_test.metrics: + micro_test_data["metrics"] = micro_metrics_data = {} + for key, value in micro_test.metrics.items(): + micro_metrics_data[key] = value.todata() + + tests_data.append(micro_test_data) + + tests_data.append(test_data) + + with open(self.output_file, "w") as file: + json.dump(data, file, indent=2, sort_keys=True) + file.write("\n") + + +_invalid_xml_chars_dict = { + c: None for c in range(32) if chr(c) not in ("\t", "\n", "\r") +} + + +def remove_invalid_xml_chars(s): + # According to the XML 1.0 spec, control characters other than + # \t,\r, and \n are not permitted anywhere in the document + # (https://www.w3.org/TR/xml/#charsets) and therefore this function + # removes them to produce a valid XML document. + # + # Note: In XML 1.1 only \0 is illegal (https://www.w3.org/TR/xml11/#charsets) + # but lit currently produces XML 1.0 output. + return s.translate(_invalid_xml_chars_dict) + + +class XunitReport(object): + def __init__(self, output_file): + self.output_file = output_file + self.skipped_codes = {lit.Test.EXCLUDED, lit.Test.SKIPPED, lit.Test.UNSUPPORTED} + + def write_results(self, tests, elapsed): + tests.sort(key=by_suite_and_test_path) + tests_by_suite = itertools.groupby(tests, lambda t: t.suite) + + with open(self.output_file, "w") as file: + file.write('\n') + file.write('\n'.format(time=elapsed)) + for suite, test_iter in tests_by_suite: + self._write_testsuite(file, suite, list(test_iter)) + file.write("\n") + + def _write_testsuite(self, file, suite, tests): + skipped = sum(1 for t in tests if t.result.code in self.skipped_codes) + failures = sum(1 for t in tests if t.isFailure()) + + name = suite.config.name.replace(".", "-") + file.write( + f'\n' + ) + for test in tests: + self._write_test(file, test, name) + file.write("\n") + + def _write_test(self, file, test, suite_name): + path = "/".join(test.path_in_suite[:-1]).replace(".", "_") + class_name = f"{suite_name}.{path or suite_name}" + name = test.path_in_suite[-1] + time = test.result.elapsed or 0.0 + file.write( + f'\n ", "]]]]>") + if isinstance(output, bytes): + output = output.decode("utf-8", "ignore") + + # Failing test output sometimes contains control characters like + # \x1b (e.g. if there was some -fcolor-diagnostics output) which are + # not allowed inside XML files. + # This causes problems with CI systems: for example, the Jenkins + # JUnit XML will throw an exception when ecountering those + # characters and similar problems also occur with GitLab CI. + output = remove_invalid_xml_chars(output) + file.write(output) + file.write("]]>\n\n") + elif test.result.code in self.skipped_codes: + reason = self._get_skip_reason(test) + file.write(f">\n \n\n") + else: + file.write("/>\n") + + def _get_skip_reason(self, test): + code = test.result.code + if code == lit.Test.EXCLUDED: + return "Test not selected (--filter, --max-tests)" + if code == lit.Test.SKIPPED: + return "User interrupt" + + assert code == lit.Test.UNSUPPORTED + features = test.getMissingRequiredFeatures() + if features: + return "Missing required feature(s): " + ", ".join(features) + return "Unsupported configuration" + + +def gen_resultdb_test_entry( + test_name, start_time, elapsed_time, test_output, result_code, is_expected +): + test_data = { + "testId": test_name, + "start_time": datetime.datetime.fromtimestamp(start_time).isoformat() + "Z", + "duration": "%.9fs" % elapsed_time, + "summary_html": '

', + "artifacts": { + "artifact-content-in-request": { + "contents": base64.b64encode(test_output.encode("utf-8")).decode( + "utf-8" + ), + }, + }, + "expected": is_expected, + } + if ( + result_code == lit.Test.PASS + or result_code == lit.Test.XPASS + or result_code == lit.Test.FLAKYPASS + ): + test_data["status"] = "PASS" + elif result_code == lit.Test.FAIL or result_code == lit.Test.XFAIL: + test_data["status"] = "FAIL" + elif ( + result_code == lit.Test.UNSUPPORTED + or result_code == lit.Test.SKIPPED + or result_code == lit.Test.EXCLUDED + ): + test_data["status"] = "SKIP" + elif result_code == lit.Test.UNRESOLVED or result_code == lit.Test.TIMEOUT: + test_data["status"] = "ABORT" + return test_data + + +class ResultDBReport(object): + def __init__(self, output_file): + self.output_file = output_file + + def write_results(self, tests, elapsed): + unexecuted_codes = {lit.Test.EXCLUDED, lit.Test.SKIPPED} + tests = [t for t in tests if t.result.code not in unexecuted_codes] + data = {} + data["__version__"] = lit.__versioninfo__ + data["elapsed"] = elapsed + # Encode the tests. + data["tests"] = tests_data = [] + for test in tests: + tests_data.append( + gen_resultdb_test_entry( + test_name=test.getFullName(), + start_time=test.result.start, + elapsed_time=test.result.elapsed, + test_output=test.result.output, + result_code=test.result.code, + is_expected=not test.result.code.isFailure, + ) + ) + if test.result.microResults: + for key, micro_test in test.result.microResults.items(): + # Expand parent test name with micro test name + parent_name = test.getFullName() + micro_full_name = parent_name + ":" + key + "microres" + tests_data.append( + gen_resultdb_test_entry( + test_name=micro_full_name, + start_time=micro_test.start + if micro_test.start + else test.result.start, + elapsed_time=micro_test.elapsed + if micro_test.elapsed + else test.result.elapsed, + test_output=micro_test.output, + result_code=micro_test.code, + is_expected=not micro_test.code.isFailure, + ) + ) + + with open(self.output_file, "w") as file: + json.dump(data, file, indent=2, sort_keys=True) + file.write("\n") + + +class TimeTraceReport(object): + def __init__(self, output_file): + self.output_file = output_file + self.skipped_codes = {lit.Test.EXCLUDED, lit.Test.SKIPPED, lit.Test.UNSUPPORTED} + + def write_results(self, tests, elapsed): + # Find when first test started so we can make start times relative. + first_start_time = min([t.result.start for t in tests]) + events = [ + self._get_test_event(x, first_start_time) + for x in tests + if x.result.code not in self.skipped_codes + ] + + json_data = {"traceEvents": events} + + with open(self.output_file, "w") as time_trace_file: + json.dump(json_data, time_trace_file, indent=2, sort_keys=True) + + def _get_test_event(self, test, first_start_time): + test_name = test.getFullName() + elapsed_time = test.result.elapsed or 0.0 + start_time = test.result.start - first_start_time if test.result.start else 0.0 + pid = test.result.pid or 0 + return { + "pid": pid, + "tid": 1, + "ph": "X", + "ts": int(start_time * 1000000.0), + "dur": int(elapsed_time * 1000000.0), + "name": test_name, + } diff --git a/wemm/lib/python3.10/site-packages/lit/util.py b/wemm/lib/python3.10/site-packages/lit/util.py new file mode 100644 index 0000000000000000000000000000000000000000..232ddc9171ad3d6af612dd7123000b31eee779a3 --- /dev/null +++ b/wemm/lib/python3.10/site-packages/lit/util.py @@ -0,0 +1,550 @@ +from __future__ import print_function + +import errno +import itertools +import math +import numbers +import os +import platform +import re +import signal +import subprocess +import sys +import threading + + +def is_string(value): + try: + # Python 2 and Python 3 are different here. + return isinstance(value, basestring) + except NameError: + return isinstance(value, str) + + +def pythonize_bool(value): + if value is None: + return False + if type(value) is bool: + return value + if isinstance(value, numbers.Number): + return value != 0 + if is_string(value): + if value.lower() in ("1", "true", "on", "yes"): + return True + if value.lower() in ("", "0", "false", "off", "no"): + return False + raise ValueError('"{}" is not a valid boolean'.format(value)) + + +def make_word_regex(word): + return r"\b" + word + r"\b" + + +def to_bytes(s): + """Return the parameter as type 'bytes', possibly encoding it. + + In Python2, the 'bytes' type is the same as 'str'. In Python3, they + are distinct. + + """ + if isinstance(s, bytes): + # In Python2, this branch is taken for both 'str' and 'bytes'. + # In Python3, this branch is taken only for 'bytes'. + return s + # In Python2, 's' is a 'unicode' object. + # In Python3, 's' is a 'str' object. + # Encode to UTF-8 to get 'bytes' data. + return s.encode("utf-8") + + +def to_string(b): + """Return the parameter as type 'str', possibly encoding it. + + In Python2, the 'str' type is the same as 'bytes'. In Python3, the + 'str' type is (essentially) Python2's 'unicode' type, and 'bytes' is + distinct. + + """ + if isinstance(b, str): + # In Python2, this branch is taken for types 'str' and 'bytes'. + # In Python3, this branch is taken only for 'str'. + return b + if isinstance(b, bytes): + # In Python2, this branch is never taken ('bytes' is handled as 'str'). + # In Python3, this is true only for 'bytes'. + try: + return b.decode("utf-8") + except UnicodeDecodeError: + # If the value is not valid Unicode, return the default + # repr-line encoding. + return str(b) + + # By this point, here's what we *don't* have: + # + # - In Python2: + # - 'str' or 'bytes' (1st branch above) + # - In Python3: + # - 'str' (1st branch above) + # - 'bytes' (2nd branch above) + # + # The last type we might expect is the Python2 'unicode' type. There is no + # 'unicode' type in Python3 (all the Python3 cases were already handled). In + # order to get a 'str' object, we need to encode the 'unicode' object. + try: + return b.encode("utf-8") + except AttributeError: + raise TypeError("not sure how to convert %s to %s" % (type(b), str)) + + +def to_unicode(s): + """Return the parameter as type which supports unicode, possibly decoding + it. + + In Python2, this is the unicode type. In Python3 it's the str type. + + """ + if isinstance(s, bytes): + # In Python2, this branch is taken for both 'str' and 'bytes'. + # In Python3, this branch is taken only for 'bytes'. + return s.decode("utf-8") + return s + + +def usable_core_count(): + """Return the number of cores the current process can use, if supported. + Otherwise, return the total number of cores (like `os.cpu_count()`). + Default to 1 if undetermined. + + """ + try: + n = len(os.sched_getaffinity(0)) + except AttributeError: + n = os.cpu_count() or 1 + + # On Windows with more than 60 processes, multiprocessing's call to + # _winapi.WaitForMultipleObjects() prints an error and lit hangs. + if platform.system() == "Windows": + return min(n, 60) + + return n + +def abs_path_preserve_drive(path): + """Return the absolute path without resolving drive mappings on Windows. + + """ + if platform.system() == "Windows": + # Windows has limitations on path length (MAX_PATH) that + # can be worked around using substitute drives, which map + # a drive letter to a longer path on another drive. + # Since Python 3.8, os.path.realpath resolves sustitute drives, + # so we should not use it. In Python 3.7, os.path.realpath + # was implemented as os.path.abspath. + return os.path.abspath(path) + else: + # On UNIX, the current directory always has symbolic links resolved, + # so any program accepting relative paths cannot preserve symbolic + # links in paths and we should always use os.path.realpath. + return os.path.realpath(path) + +def mkdir(path): + try: + if platform.system() == "Windows": + from ctypes import windll + from ctypes import GetLastError, WinError + + path = os.path.abspath(path) + # Make sure that the path uses backslashes here, in case + # python would have happened to use forward slashes, as the + # NT path format only supports backslashes. + path = path.replace("/", "\\") + NTPath = to_unicode(r"\\?\%s" % path) + if not windll.kernel32.CreateDirectoryW(NTPath, None): + raise WinError(GetLastError()) + else: + os.mkdir(path) + except OSError: + e = sys.exc_info()[1] + # ignore EEXIST, which may occur during a race condition + if e.errno != errno.EEXIST: + raise + + +def mkdir_p(path): + """mkdir_p(path) - Make the "path" directory, if it does not exist; this + will also make directories for any missing parent directories.""" + if not path or os.path.exists(path): + return + + parent = os.path.dirname(path) + if parent != path: + mkdir_p(parent) + + mkdir(path) + + +def listdir_files(dirname, suffixes=None, exclude_filenames=None): + """Yields files in a directory. + + Filenames that are not excluded by rules below are yielded one at a time, as + basenames (i.e., without dirname). + + Files starting with '.' are always skipped. + + If 'suffixes' is not None, then only filenames ending with one of its + members will be yielded. These can be extensions, like '.exe', or strings, + like 'Test'. (It is a lexicographic check; so an empty sequence will yield + nothing, but a single empty string will yield all filenames.) + + If 'exclude_filenames' is not None, then none of the file basenames in it + will be yielded. + + If specified, the containers for 'suffixes' and 'exclude_filenames' must + support membership checking for strs. + + Args: + dirname: a directory path. + suffixes: (optional) a sequence of strings (set, list, etc.). + exclude_filenames: (optional) a sequence of strings. + + Yields: + Filenames as returned by os.listdir (generally, str). + + """ + if exclude_filenames is None: + exclude_filenames = set() + if suffixes is None: + suffixes = {""} + for filename in os.listdir(dirname): + if ( + os.path.isdir(os.path.join(dirname, filename)) + or filename.startswith(".") + or filename in exclude_filenames + or not any(filename.endswith(sfx) for sfx in suffixes) + ): + continue + yield filename + + +def which(command, paths=None): + """which(command, [paths]) - Look up the given command in the paths string + (or the PATH environment variable, if unspecified).""" + + if paths is None: + paths = os.environ.get("PATH", "") + + # Check for absolute match first. + if os.path.isabs(command) and os.path.isfile(command): + return os.path.normcase(os.path.normpath(command)) + + # Would be nice if Python had a lib function for this. + if not paths: + paths = os.defpath + + # Get suffixes to search. + # On Cygwin, 'PATHEXT' may exist but it should not be used. + if os.pathsep == ";": + pathext = os.environ.get("PATHEXT", "").split(";") + else: + pathext = [""] + + # Search the paths... + for path in paths.split(os.pathsep): + for ext in pathext: + p = os.path.join(path, command + ext) + if os.path.exists(p) and not os.path.isdir(p): + return os.path.normcase(os.path.abspath(p)) + + return None + + +def checkToolsPath(dir, tools): + for tool in tools: + if not os.path.exists(os.path.join(dir, tool)): + return False + return True + + +def whichTools(tools, paths): + for path in paths.split(os.pathsep): + if checkToolsPath(path, tools): + return path + return None + + +def printHistogram(items, title="Items"): + items.sort(key=lambda item: item[1]) + + maxValue = max([v for _, v in items]) + + # Select first "nice" bar height that produces more than 10 bars. + power = int(math.ceil(math.log(maxValue, 10))) + for inc in itertools.cycle((5, 2, 2.5, 1)): + barH = inc * 10**power + N = int(math.ceil(maxValue / barH)) + if N > 10: + break + elif inc == 1: + power -= 1 + + histo = [set() for i in range(N)] + for name, v in items: + bin = min(int(N * v / maxValue), N - 1) + histo[bin].add(name) + + barW = 40 + hr = "-" * (barW + 34) + print("Slowest %s:" % title) + print(hr) + for name, value in reversed(items[-20:]): + print("%.2fs: %s" % (value, name)) + print("\n%s Times:" % title) + print(hr) + pDigits = int(math.ceil(math.log(maxValue, 10))) + pfDigits = max(0, 3 - pDigits) + if pfDigits: + pDigits += pfDigits + 1 + cDigits = int(math.ceil(math.log(len(items), 10))) + print( + "[%s] :: [%s] :: [%s]" + % ( + "Range".center((pDigits + 1) * 2 + 3), + "Percentage".center(barW), + "Count".center(cDigits * 2 + 1), + ) + ) + print(hr) + for i, row in reversed(list(enumerate(histo))): + pct = float(len(row)) / len(items) + w = int(barW * pct) + print( + "[%*.*fs,%*.*fs) :: [%s%s] :: [%*d/%*d]" + % ( + pDigits, + pfDigits, + i * barH, + pDigits, + pfDigits, + (i + 1) * barH, + "*" * w, + " " * (barW - w), + cDigits, + len(row), + cDigits, + len(items), + ) + ) + print(hr) + + +class ExecuteCommandTimeoutException(Exception): + def __init__(self, msg, out, err, exitCode): + assert isinstance(msg, str) + assert isinstance(out, str) + assert isinstance(err, str) + assert isinstance(exitCode, int) + self.msg = msg + self.out = out + self.err = err + self.exitCode = exitCode + + +# Close extra file handles on UNIX (on Windows this cannot be done while +# also redirecting input). +kUseCloseFDs = not (platform.system() == "Windows") + + +def executeCommand( + command, cwd=None, env=None, input=None, timeout=0, redirect_stderr=False +): + """Execute command ``command`` (list of arguments or string) with. + + * working directory ``cwd`` (str), use None to use the current + working directory + * environment ``env`` (dict), use None for none + * Input to the command ``input`` (str), use string to pass + no input. + * Max execution time ``timeout`` (int) seconds. Use 0 for no timeout. + * ``redirect_stderr`` (bool), use True if redirect stderr to stdout + + Returns a tuple (out, err, exitCode) where + * ``out`` (str) is the standard output of running the command + * ``err`` (str) is the standard error of running the command + * ``exitCode`` (int) is the exitCode of running the command + + If the timeout is hit an ``ExecuteCommandTimeoutException`` + is raised. + + """ + if input is not None: + input = to_bytes(input) + err_out = subprocess.STDOUT if redirect_stderr else subprocess.PIPE + p = subprocess.Popen( + command, + cwd=cwd, + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=err_out, + env=env, + close_fds=kUseCloseFDs, + ) + timerObject = None + # FIXME: Because of the way nested function scopes work in Python 2.x we + # need to use a reference to a mutable object rather than a plain + # bool. In Python 3 we could use the "nonlocal" keyword but we need + # to support Python 2 as well. + hitTimeOut = [False] + try: + if timeout > 0: + + def killProcess(): + # We may be invoking a shell so we need to kill the + # process and all its children. + hitTimeOut[0] = True + killProcessAndChildren(p.pid) + + timerObject = threading.Timer(timeout, killProcess) + timerObject.start() + + out, err = p.communicate(input=input) + exitCode = p.wait() + finally: + if timerObject != None: + timerObject.cancel() + + # Ensure the resulting output is always of string type. + out = to_string(out) + err = "" if redirect_stderr else to_string(err) + + if hitTimeOut[0]: + raise ExecuteCommandTimeoutException( + msg="Reached timeout of {} seconds".format(timeout), + out=out, + err=err, + exitCode=exitCode, + ) + + # Detect Ctrl-C in subprocess. + if exitCode == -signal.SIGINT: + raise KeyboardInterrupt + + return out, err, exitCode + + +def isAIXTriple(target_triple): + """Whether the given target triple is for AIX, + e.g. powerpc64-ibm-aix + """ + return "aix" in target_triple + + +def addAIXVersion(target_triple): + """Add the AIX version to the given target triple, + e.g. powerpc64-ibm-aix7.2.5.6 + """ + os_cmd = "oslevel -s | awk -F\'-\' \'{printf \"%.1f.%d.%d\", $1/1000, $2, $3}\'" + os_version = subprocess.run(os_cmd, capture_output=True, shell=True).stdout.decode() + return re.sub("aix", "aix" + os_version, target_triple) + + +def isMacOSTriple(target_triple): + """Whether the given target triple is for macOS, + e.g. x86_64-apple-darwin, arm64-apple-macos + """ + return "darwin" in target_triple or "macos" in target_triple + + +def usePlatformSdkOnDarwin(config, lit_config): + # On Darwin, support relocatable SDKs by providing Clang with a + # default system root path. + if isMacOSTriple(config.target_triple): + try: + cmd = subprocess.Popen( + ["xcrun", "--show-sdk-path", "--sdk", "macosx"], + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + ) + out, err = cmd.communicate() + out = out.strip() + res = cmd.wait() + except OSError: + res = -1 + if res == 0 and out: + sdk_path = out.decode() + lit_config.note("using SDKROOT: %r" % sdk_path) + config.environment["SDKROOT"] = sdk_path + + +def findPlatformSdkVersionOnMacOS(config, lit_config): + if isMacOSTriple(config.target_triple): + try: + cmd = subprocess.Popen( + ["xcrun", "--show-sdk-version", "--sdk", "macosx"], + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + ) + out, err = cmd.communicate() + out = out.strip() + res = cmd.wait() + except OSError: + res = -1 + if res == 0 and out: + return out.decode() + return None + + +def killProcessAndChildrenIsSupported(): + """ + Returns a tuple ( , ) + where + `` is True if `killProcessAndChildren()` is supported on + the current host, returns False otherwise. + `` is an empty string if `` is True, + otherwise is contains a string describing why the function is + not supported. + """ + if platform.system() == "AIX": + return (True, "") + try: + import psutil # noqa: F401 + + return (True, "") + except ImportError: + return ( + False, + "Requires the Python psutil module but it could" + " not be found. Try installing it via pip or via" + " your operating system's package manager.", + ) + + +def killProcessAndChildren(pid): + """This function kills a process with ``pid`` and all its running children + (recursively). It is currently implemented using the psutil module on some + platforms which provides a simple platform neutral implementation. + + TODO: Reimplement this without using psutil on all platforms so we can + remove our dependency on it. + + """ + if platform.system() == "AIX": + subprocess.call("kill -kill $(ps -o pid= -L{})".format(pid), shell=True) + else: + import psutil + + try: + psutilProc = psutil.Process(pid) + # Handle the different psutil API versions + try: + # psutil >= 2.x + children_iterator = psutilProc.children(recursive=True) + except AttributeError: + # psutil 1.x + children_iterator = psutilProc.get_children(recursive=True) + for child in children_iterator: + try: + child.kill() + except psutil.NoSuchProcess: + pass + psutilProc.kill() + except psutil.NoSuchProcess: + pass diff --git a/wemm/lib/python3.10/site-packages/lit/worker.py b/wemm/lib/python3.10/site-packages/lit/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..8e78bfd45d38bd2e36abeb3ce83989b7febab1d5 --- /dev/null +++ b/wemm/lib/python3.10/site-packages/lit/worker.py @@ -0,0 +1,94 @@ +""" +The functions in this module are meant to run on a separate worker process. +Exception: in single process mode _execute is called directly. + +For efficiency, we copy all data needed to execute all tests into each worker +and store it in global variables. This reduces the cost of each task. +""" +import contextlib +import os +import signal +import time +import traceback + +import lit.Test +import lit.util + + +_lit_config = None +_parallelism_semaphores = None + + +def initialize(lit_config, parallelism_semaphores): + """Copy data shared by all test executions into worker processes""" + global _lit_config + global _parallelism_semaphores + _lit_config = lit_config + _parallelism_semaphores = parallelism_semaphores + + # We use the following strategy for dealing with Ctrl+C/KeyboardInterrupt in + # subprocesses created by the multiprocessing.Pool. + # https://noswap.com/blog/python-multiprocessing-keyboardinterrupt + signal.signal(signal.SIGINT, signal.SIG_IGN) + + +def execute(test): + """Run one test in a multiprocessing.Pool + + Side effects in this function and functions it calls are not visible in the + main lit process. + + Arguments and results of this function are pickled, so they should be cheap + to copy. + """ + with _get_parallelism_semaphore(test): + result = _execute(test, _lit_config) + + test.setResult(result) + return test + + +# TODO(python3): replace with contextlib.nullcontext +@contextlib.contextmanager +def NopSemaphore(): + yield + + +def _get_parallelism_semaphore(test): + pg = test.config.parallelism_group + if callable(pg): + pg = pg(test) + return _parallelism_semaphores.get(pg, NopSemaphore()) + + +# Do not inline! Directly used by LitTestCase.py +def _execute(test, lit_config): + start = time.time() + result = _execute_test_handle_errors(test, lit_config) + result.elapsed = time.time() - start + result.start = start + result.pid = os.getpid() + return result + + +def _execute_test_handle_errors(test, lit_config): + try: + result = test.config.test_format.execute(test, lit_config) + return _adapt_result(result) + except: + if lit_config.debug: + raise + output = "Exception during script execution:\n" + output += traceback.format_exc() + output += "\n" + return lit.Test.Result(lit.Test.UNRESOLVED, output) + + +# Support deprecated result from execute() which returned the result +# code and additional output as a tuple. +def _adapt_result(result): + if isinstance(result, lit.Test.Result): + return result + assert isinstance(result, tuple) + code, output = result + return lit.Test.Result(code, output) diff --git a/wemm/lib/python3.10/site-packages/nvidia_cusolver_cu12-11.4.5.107.dist-info/WHEEL b/wemm/lib/python3.10/site-packages/nvidia_cusolver_cu12-11.4.5.107.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..06e355fe0e3ed7077903f119ae6928a17da8eb6f --- /dev/null +++ b/wemm/lib/python3.10/site-packages/nvidia_cusolver_cu12-11.4.5.107.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: bdist_wheel (0.37.1) +Root-Is-Purelib: true +Tag: py3-none-manylinux1_x86_64 + diff --git a/wemm/lib/python3.10/site-packages/requests/__init__.py b/wemm/lib/python3.10/site-packages/requests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..051cda1340effaa0706b46dd68ac002ceda3d45c --- /dev/null +++ b/wemm/lib/python3.10/site-packages/requests/__init__.py @@ -0,0 +1,184 @@ +# __ +# /__) _ _ _ _ _/ _ +# / ( (- (/ (/ (- _) / _) +# / + +""" +Requests HTTP Library +~~~~~~~~~~~~~~~~~~~~~ + +Requests is an HTTP library, written in Python, for human beings. +Basic GET usage: + + >>> import requests + >>> r = requests.get('https://www.python.org') + >>> r.status_code + 200 + >>> b'Python is a programming language' in r.content + True + +... or POST: + + >>> payload = dict(key1='value1', key2='value2') + >>> r = requests.post('https://httpbin.org/post', data=payload) + >>> print(r.text) + { + ... + "form": { + "key1": "value1", + "key2": "value2" + }, + ... + } + +The other HTTP methods are supported - see `requests.api`. Full documentation +is at . + +:copyright: (c) 2017 by Kenneth Reitz. +:license: Apache 2.0, see LICENSE for more details. +""" + +import warnings + +import urllib3 + +from .exceptions import RequestsDependencyWarning + +try: + from charset_normalizer import __version__ as charset_normalizer_version +except ImportError: + charset_normalizer_version = None + +try: + from chardet import __version__ as chardet_version +except ImportError: + chardet_version = None + + +def check_compatibility(urllib3_version, chardet_version, charset_normalizer_version): + urllib3_version = urllib3_version.split(".") + assert urllib3_version != ["dev"] # Verify urllib3 isn't installed from git. + + # Sometimes, urllib3 only reports its version as 16.1. + if len(urllib3_version) == 2: + urllib3_version.append("0") + + # Check urllib3 for compatibility. + major, minor, patch = urllib3_version # noqa: F811 + major, minor, patch = int(major), int(minor), int(patch) + # urllib3 >= 1.21.1 + assert major >= 1 + if major == 1: + assert minor >= 21 + + # Check charset_normalizer for compatibility. + if chardet_version: + major, minor, patch = chardet_version.split(".")[:3] + major, minor, patch = int(major), int(minor), int(patch) + # chardet_version >= 3.0.2, < 6.0.0 + assert (3, 0, 2) <= (major, minor, patch) < (6, 0, 0) + elif charset_normalizer_version: + major, minor, patch = charset_normalizer_version.split(".")[:3] + major, minor, patch = int(major), int(minor), int(patch) + # charset_normalizer >= 2.0.0 < 4.0.0 + assert (2, 0, 0) <= (major, minor, patch) < (4, 0, 0) + else: + warnings.warn( + "Unable to find acceptable character detection dependency " + "(chardet or charset_normalizer).", + RequestsDependencyWarning, + ) + + +def _check_cryptography(cryptography_version): + # cryptography < 1.3.4 + try: + cryptography_version = list(map(int, cryptography_version.split("."))) + except ValueError: + return + + if cryptography_version < [1, 3, 4]: + warning = "Old version of cryptography ({}) may cause slowdown.".format( + cryptography_version + ) + warnings.warn(warning, RequestsDependencyWarning) + + +# Check imported dependencies for compatibility. +try: + check_compatibility( + urllib3.__version__, chardet_version, charset_normalizer_version + ) +except (AssertionError, ValueError): + warnings.warn( + "urllib3 ({}) or chardet ({})/charset_normalizer ({}) doesn't match a supported " + "version!".format( + urllib3.__version__, chardet_version, charset_normalizer_version + ), + RequestsDependencyWarning, + ) + +# Attempt to enable urllib3's fallback for SNI support +# if the standard library doesn't support SNI or the +# 'ssl' library isn't available. +try: + try: + import ssl + except ImportError: + ssl = None + + if not getattr(ssl, "HAS_SNI", False): + from urllib3.contrib import pyopenssl + + pyopenssl.inject_into_urllib3() + + # Check cryptography version + from cryptography import __version__ as cryptography_version + + _check_cryptography(cryptography_version) +except ImportError: + pass + +# urllib3's DependencyWarnings should be silenced. +from urllib3.exceptions import DependencyWarning + +warnings.simplefilter("ignore", DependencyWarning) + +# Set default logging handler to avoid "No handler found" warnings. +import logging +from logging import NullHandler + +from . import packages, utils +from .__version__ import ( + __author__, + __author_email__, + __build__, + __cake__, + __copyright__, + __description__, + __license__, + __title__, + __url__, + __version__, +) +from .api import delete, get, head, options, patch, post, put, request +from .exceptions import ( + ConnectionError, + ConnectTimeout, + FileModeWarning, + HTTPError, + JSONDecodeError, + ReadTimeout, + RequestException, + Timeout, + TooManyRedirects, + URLRequired, +) +from .models import PreparedRequest, Request, Response +from .sessions import Session, session +from .status_codes import codes + +logging.getLogger(__name__).addHandler(NullHandler()) + +# FileModeWarnings go off per the default. +warnings.simplefilter("default", FileModeWarning, append=True) diff --git a/wemm/lib/python3.10/site-packages/requests/__pycache__/_internal_utils.cpython-310.pyc b/wemm/lib/python3.10/site-packages/requests/__pycache__/_internal_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1dc993c050422455f41b46184cb52b98343df01e Binary files /dev/null and b/wemm/lib/python3.10/site-packages/requests/__pycache__/_internal_utils.cpython-310.pyc differ diff --git a/wemm/lib/python3.10/site-packages/requests/__pycache__/help.cpython-310.pyc b/wemm/lib/python3.10/site-packages/requests/__pycache__/help.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7364fba8e739f335a02b7bcc831e864197cddb5e Binary files /dev/null and b/wemm/lib/python3.10/site-packages/requests/__pycache__/help.cpython-310.pyc differ diff --git a/wemm/lib/python3.10/site-packages/requests/__pycache__/status_codes.cpython-310.pyc b/wemm/lib/python3.10/site-packages/requests/__pycache__/status_codes.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..83162f252f64e9b31d418531dd7f8934d0d0a87e Binary files /dev/null and b/wemm/lib/python3.10/site-packages/requests/__pycache__/status_codes.cpython-310.pyc differ diff --git a/wemm/lib/python3.10/site-packages/requests/__version__.py b/wemm/lib/python3.10/site-packages/requests/__version__.py new file mode 100644 index 0000000000000000000000000000000000000000..2c105aca7d48ce1c35a456785cc75f97f076a426 --- /dev/null +++ b/wemm/lib/python3.10/site-packages/requests/__version__.py @@ -0,0 +1,14 @@ +# .-. .-. .-. . . .-. .-. .-. .-. +# |( |- |.| | | |- `-. | `-. +# ' ' `-' `-`.`-' `-' `-' ' `-' + +__title__ = "requests" +__description__ = "Python HTTP for Humans." +__url__ = "https://requests.readthedocs.io" +__version__ = "2.32.3" +__build__ = 0x023203 +__author__ = "Kenneth Reitz" +__author_email__ = "me@kennethreitz.org" +__license__ = "Apache-2.0" +__copyright__ = "Copyright Kenneth Reitz" +__cake__ = "\u2728 \U0001f370 \u2728" diff --git a/wemm/lib/python3.10/site-packages/requests/_internal_utils.py b/wemm/lib/python3.10/site-packages/requests/_internal_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..f2cf635e2937ee9b123a1498c5c5f723a6e20084 --- /dev/null +++ b/wemm/lib/python3.10/site-packages/requests/_internal_utils.py @@ -0,0 +1,50 @@ +""" +requests._internal_utils +~~~~~~~~~~~~~~ + +Provides utility functions that are consumed internally by Requests +which depend on extremely few external helpers (such as compat) +""" +import re + +from .compat import builtin_str + +_VALID_HEADER_NAME_RE_BYTE = re.compile(rb"^[^:\s][^:\r\n]*$") +_VALID_HEADER_NAME_RE_STR = re.compile(r"^[^:\s][^:\r\n]*$") +_VALID_HEADER_VALUE_RE_BYTE = re.compile(rb"^\S[^\r\n]*$|^$") +_VALID_HEADER_VALUE_RE_STR = re.compile(r"^\S[^\r\n]*$|^$") + +_HEADER_VALIDATORS_STR = (_VALID_HEADER_NAME_RE_STR, _VALID_HEADER_VALUE_RE_STR) +_HEADER_VALIDATORS_BYTE = (_VALID_HEADER_NAME_RE_BYTE, _VALID_HEADER_VALUE_RE_BYTE) +HEADER_VALIDATORS = { + bytes: _HEADER_VALIDATORS_BYTE, + str: _HEADER_VALIDATORS_STR, +} + + +def to_native_string(string, encoding="ascii"): + """Given a string object, regardless of type, returns a representation of + that string in the native string type, encoding and decoding where + necessary. This assumes ASCII unless told otherwise. + """ + if isinstance(string, builtin_str): + out = string + else: + out = string.decode(encoding) + + return out + + +def unicode_is_ascii(u_string): + """Determine if unicode string only contains ASCII characters. + + :param str u_string: unicode string to check. Must be unicode + and not Python 2 `str`. + :rtype: bool + """ + assert isinstance(u_string, str) + try: + u_string.encode("ascii") + return True + except UnicodeEncodeError: + return False diff --git a/wemm/lib/python3.10/site-packages/requests/adapters.py b/wemm/lib/python3.10/site-packages/requests/adapters.py new file mode 100644 index 0000000000000000000000000000000000000000..9a58b1602532f9bee41afb0dfadaa7eb548e98c1 --- /dev/null +++ b/wemm/lib/python3.10/site-packages/requests/adapters.py @@ -0,0 +1,719 @@ +""" +requests.adapters +~~~~~~~~~~~~~~~~~ + +This module contains the transport adapters that Requests uses to define +and maintain connections. +""" + +import os.path +import socket # noqa: F401 +import typing +import warnings + +from urllib3.exceptions import ClosedPoolError, ConnectTimeoutError +from urllib3.exceptions import HTTPError as _HTTPError +from urllib3.exceptions import InvalidHeader as _InvalidHeader +from urllib3.exceptions import ( + LocationValueError, + MaxRetryError, + NewConnectionError, + ProtocolError, +) +from urllib3.exceptions import ProxyError as _ProxyError +from urllib3.exceptions import ReadTimeoutError, ResponseError +from urllib3.exceptions import SSLError as _SSLError +from urllib3.poolmanager import PoolManager, proxy_from_url +from urllib3.util import Timeout as TimeoutSauce +from urllib3.util import parse_url +from urllib3.util.retry import Retry +from urllib3.util.ssl_ import create_urllib3_context + +from .auth import _basic_auth_str +from .compat import basestring, urlparse +from .cookies import extract_cookies_to_jar +from .exceptions import ( + ConnectionError, + ConnectTimeout, + InvalidHeader, + InvalidProxyURL, + InvalidSchema, + InvalidURL, + ProxyError, + ReadTimeout, + RetryError, + SSLError, +) +from .models import Response +from .structures import CaseInsensitiveDict +from .utils import ( + DEFAULT_CA_BUNDLE_PATH, + extract_zipped_paths, + get_auth_from_url, + get_encoding_from_headers, + prepend_scheme_if_needed, + select_proxy, + urldefragauth, +) + +try: + from urllib3.contrib.socks import SOCKSProxyManager +except ImportError: + + def SOCKSProxyManager(*args, **kwargs): + raise InvalidSchema("Missing dependencies for SOCKS support.") + + +if typing.TYPE_CHECKING: + from .models import PreparedRequest + + +DEFAULT_POOLBLOCK = False +DEFAULT_POOLSIZE = 10 +DEFAULT_RETRIES = 0 +DEFAULT_POOL_TIMEOUT = None + + +try: + import ssl # noqa: F401 + + _preloaded_ssl_context = create_urllib3_context() + _preloaded_ssl_context.load_verify_locations( + extract_zipped_paths(DEFAULT_CA_BUNDLE_PATH) + ) +except ImportError: + # Bypass default SSLContext creation when Python + # interpreter isn't built with the ssl module. + _preloaded_ssl_context = None + + +def _urllib3_request_context( + request: "PreparedRequest", + verify: "bool | str | None", + client_cert: "typing.Tuple[str, str] | str | None", + poolmanager: "PoolManager", +) -> "(typing.Dict[str, typing.Any], typing.Dict[str, typing.Any])": + host_params = {} + pool_kwargs = {} + parsed_request_url = urlparse(request.url) + scheme = parsed_request_url.scheme.lower() + port = parsed_request_url.port + + # Determine if we have and should use our default SSLContext + # to optimize performance on standard requests. + poolmanager_kwargs = getattr(poolmanager, "connection_pool_kw", {}) + has_poolmanager_ssl_context = poolmanager_kwargs.get("ssl_context") + should_use_default_ssl_context = ( + _preloaded_ssl_context is not None and not has_poolmanager_ssl_context + ) + + cert_reqs = "CERT_REQUIRED" + if verify is False: + cert_reqs = "CERT_NONE" + elif verify is True and should_use_default_ssl_context: + pool_kwargs["ssl_context"] = _preloaded_ssl_context + elif isinstance(verify, str): + if not os.path.isdir(verify): + pool_kwargs["ca_certs"] = verify + else: + pool_kwargs["ca_cert_dir"] = verify + pool_kwargs["cert_reqs"] = cert_reqs + if client_cert is not None: + if isinstance(client_cert, tuple) and len(client_cert) == 2: + pool_kwargs["cert_file"] = client_cert[0] + pool_kwargs["key_file"] = client_cert[1] + else: + # According to our docs, we allow users to specify just the client + # cert path + pool_kwargs["cert_file"] = client_cert + host_params = { + "scheme": scheme, + "host": parsed_request_url.hostname, + "port": port, + } + return host_params, pool_kwargs + + +class BaseAdapter: + """The Base Transport Adapter""" + + def __init__(self): + super().__init__() + + def send( + self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None + ): + """Sends PreparedRequest object. Returns Response object. + + :param request: The :class:`PreparedRequest ` being sent. + :param stream: (optional) Whether to stream the request content. + :param timeout: (optional) How long to wait for the server to send + data before giving up, as a float, or a :ref:`(connect timeout, + read timeout) ` tuple. + :type timeout: float or tuple + :param verify: (optional) Either a boolean, in which case it controls whether we verify + the server's TLS certificate, or a string, in which case it must be a path + to a CA bundle to use + :param cert: (optional) Any user-provided SSL certificate to be trusted. + :param proxies: (optional) The proxies dictionary to apply to the request. + """ + raise NotImplementedError + + def close(self): + """Cleans up adapter specific items.""" + raise NotImplementedError + + +class HTTPAdapter(BaseAdapter): + """The built-in HTTP Adapter for urllib3. + + Provides a general-case interface for Requests sessions to contact HTTP and + HTTPS urls by implementing the Transport Adapter interface. This class will + usually be created by the :class:`Session ` class under the + covers. + + :param pool_connections: The number of urllib3 connection pools to cache. + :param pool_maxsize: The maximum number of connections to save in the pool. + :param max_retries: The maximum number of retries each connection + should attempt. Note, this applies only to failed DNS lookups, socket + connections and connection timeouts, never to requests where data has + made it to the server. By default, Requests does not retry failed + connections. If you need granular control over the conditions under + which we retry a request, import urllib3's ``Retry`` class and pass + that instead. + :param pool_block: Whether the connection pool should block for connections. + + Usage:: + + >>> import requests + >>> s = requests.Session() + >>> a = requests.adapters.HTTPAdapter(max_retries=3) + >>> s.mount('http://', a) + """ + + __attrs__ = [ + "max_retries", + "config", + "_pool_connections", + "_pool_maxsize", + "_pool_block", + ] + + def __init__( + self, + pool_connections=DEFAULT_POOLSIZE, + pool_maxsize=DEFAULT_POOLSIZE, + max_retries=DEFAULT_RETRIES, + pool_block=DEFAULT_POOLBLOCK, + ): + if max_retries == DEFAULT_RETRIES: + self.max_retries = Retry(0, read=False) + else: + self.max_retries = Retry.from_int(max_retries) + self.config = {} + self.proxy_manager = {} + + super().__init__() + + self._pool_connections = pool_connections + self._pool_maxsize = pool_maxsize + self._pool_block = pool_block + + self.init_poolmanager(pool_connections, pool_maxsize, block=pool_block) + + def __getstate__(self): + return {attr: getattr(self, attr, None) for attr in self.__attrs__} + + def __setstate__(self, state): + # Can't handle by adding 'proxy_manager' to self.__attrs__ because + # self.poolmanager uses a lambda function, which isn't pickleable. + self.proxy_manager = {} + self.config = {} + + for attr, value in state.items(): + setattr(self, attr, value) + + self.init_poolmanager( + self._pool_connections, self._pool_maxsize, block=self._pool_block + ) + + def init_poolmanager( + self, connections, maxsize, block=DEFAULT_POOLBLOCK, **pool_kwargs + ): + """Initializes a urllib3 PoolManager. + + This method should not be called from user code, and is only + exposed for use when subclassing the + :class:`HTTPAdapter `. + + :param connections: The number of urllib3 connection pools to cache. + :param maxsize: The maximum number of connections to save in the pool. + :param block: Block when no free connections are available. + :param pool_kwargs: Extra keyword arguments used to initialize the Pool Manager. + """ + # save these values for pickling + self._pool_connections = connections + self._pool_maxsize = maxsize + self._pool_block = block + + self.poolmanager = PoolManager( + num_pools=connections, + maxsize=maxsize, + block=block, + **pool_kwargs, + ) + + def proxy_manager_for(self, proxy, **proxy_kwargs): + """Return urllib3 ProxyManager for the given proxy. + + This method should not be called from user code, and is only + exposed for use when subclassing the + :class:`HTTPAdapter `. + + :param proxy: The proxy to return a urllib3 ProxyManager for. + :param proxy_kwargs: Extra keyword arguments used to configure the Proxy Manager. + :returns: ProxyManager + :rtype: urllib3.ProxyManager + """ + if proxy in self.proxy_manager: + manager = self.proxy_manager[proxy] + elif proxy.lower().startswith("socks"): + username, password = get_auth_from_url(proxy) + manager = self.proxy_manager[proxy] = SOCKSProxyManager( + proxy, + username=username, + password=password, + num_pools=self._pool_connections, + maxsize=self._pool_maxsize, + block=self._pool_block, + **proxy_kwargs, + ) + else: + proxy_headers = self.proxy_headers(proxy) + manager = self.proxy_manager[proxy] = proxy_from_url( + proxy, + proxy_headers=proxy_headers, + num_pools=self._pool_connections, + maxsize=self._pool_maxsize, + block=self._pool_block, + **proxy_kwargs, + ) + + return manager + + def cert_verify(self, conn, url, verify, cert): + """Verify a SSL certificate. This method should not be called from user + code, and is only exposed for use when subclassing the + :class:`HTTPAdapter `. + + :param conn: The urllib3 connection object associated with the cert. + :param url: The requested URL. + :param verify: Either a boolean, in which case it controls whether we verify + the server's TLS certificate, or a string, in which case it must be a path + to a CA bundle to use + :param cert: The SSL certificate to verify. + """ + if url.lower().startswith("https") and verify: + conn.cert_reqs = "CERT_REQUIRED" + + # Only load the CA certificates if 'verify' is a string indicating the CA bundle to use. + # Otherwise, if verify is a boolean, we don't load anything since + # the connection will be using a context with the default certificates already loaded, + # and this avoids a call to the slow load_verify_locations() + if verify is not True: + # `verify` must be a str with a path then + cert_loc = verify + + if not os.path.exists(cert_loc): + raise OSError( + f"Could not find a suitable TLS CA certificate bundle, " + f"invalid path: {cert_loc}" + ) + + if not os.path.isdir(cert_loc): + conn.ca_certs = cert_loc + else: + conn.ca_cert_dir = cert_loc + else: + conn.cert_reqs = "CERT_NONE" + conn.ca_certs = None + conn.ca_cert_dir = None + + if cert: + if not isinstance(cert, basestring): + conn.cert_file = cert[0] + conn.key_file = cert[1] + else: + conn.cert_file = cert + conn.key_file = None + if conn.cert_file and not os.path.exists(conn.cert_file): + raise OSError( + f"Could not find the TLS certificate file, " + f"invalid path: {conn.cert_file}" + ) + if conn.key_file and not os.path.exists(conn.key_file): + raise OSError( + f"Could not find the TLS key file, invalid path: {conn.key_file}" + ) + + def build_response(self, req, resp): + """Builds a :class:`Response ` object from a urllib3 + response. This should not be called from user code, and is only exposed + for use when subclassing the + :class:`HTTPAdapter ` + + :param req: The :class:`PreparedRequest ` used to generate the response. + :param resp: The urllib3 response object. + :rtype: requests.Response + """ + response = Response() + + # Fallback to None if there's no status_code, for whatever reason. + response.status_code = getattr(resp, "status", None) + + # Make headers case-insensitive. + response.headers = CaseInsensitiveDict(getattr(resp, "headers", {})) + + # Set encoding. + response.encoding = get_encoding_from_headers(response.headers) + response.raw = resp + response.reason = response.raw.reason + + if isinstance(req.url, bytes): + response.url = req.url.decode("utf-8") + else: + response.url = req.url + + # Add new cookies from the server. + extract_cookies_to_jar(response.cookies, req, resp) + + # Give the Response some context. + response.request = req + response.connection = self + + return response + + def build_connection_pool_key_attributes(self, request, verify, cert=None): + """Build the PoolKey attributes used by urllib3 to return a connection. + + This looks at the PreparedRequest, the user-specified verify value, + and the value of the cert parameter to determine what PoolKey values + to use to select a connection from a given urllib3 Connection Pool. + + The SSL related pool key arguments are not consistently set. As of + this writing, use the following to determine what keys may be in that + dictionary: + + * If ``verify`` is ``True``, ``"ssl_context"`` will be set and will be the + default Requests SSL Context + * If ``verify`` is ``False``, ``"ssl_context"`` will not be set but + ``"cert_reqs"`` will be set + * If ``verify`` is a string, (i.e., it is a user-specified trust bundle) + ``"ca_certs"`` will be set if the string is not a directory recognized + by :py:func:`os.path.isdir`, otherwise ``"ca_certs_dir"`` will be + set. + * If ``"cert"`` is specified, ``"cert_file"`` will always be set. If + ``"cert"`` is a tuple with a second item, ``"key_file"`` will also + be present + + To override these settings, one may subclass this class, call this + method and use the above logic to change parameters as desired. For + example, if one wishes to use a custom :py:class:`ssl.SSLContext` one + must both set ``"ssl_context"`` and based on what else they require, + alter the other keys to ensure the desired behaviour. + + :param request: + The PreparedReqest being sent over the connection. + :type request: + :class:`~requests.models.PreparedRequest` + :param verify: + Either a boolean, in which case it controls whether + we verify the server's TLS certificate, or a string, in which case it + must be a path to a CA bundle to use. + :param cert: + (optional) Any user-provided SSL certificate for client + authentication (a.k.a., mTLS). This may be a string (i.e., just + the path to a file which holds both certificate and key) or a + tuple of length 2 with the certificate file path and key file + path. + :returns: + A tuple of two dictionaries. The first is the "host parameters" + portion of the Pool Key including scheme, hostname, and port. The + second is a dictionary of SSLContext related parameters. + """ + return _urllib3_request_context(request, verify, cert, self.poolmanager) + + def get_connection_with_tls_context(self, request, verify, proxies=None, cert=None): + """Returns a urllib3 connection for the given request and TLS settings. + This should not be called from user code, and is only exposed for use + when subclassing the :class:`HTTPAdapter `. + + :param request: + The :class:`PreparedRequest ` object to be sent + over the connection. + :param verify: + Either a boolean, in which case it controls whether we verify the + server's TLS certificate, or a string, in which case it must be a + path to a CA bundle to use. + :param proxies: + (optional) The proxies dictionary to apply to the request. + :param cert: + (optional) Any user-provided SSL certificate to be used for client + authentication (a.k.a., mTLS). + :rtype: + urllib3.ConnectionPool + """ + proxy = select_proxy(request.url, proxies) + try: + host_params, pool_kwargs = self.build_connection_pool_key_attributes( + request, + verify, + cert, + ) + except ValueError as e: + raise InvalidURL(e, request=request) + if proxy: + proxy = prepend_scheme_if_needed(proxy, "http") + proxy_url = parse_url(proxy) + if not proxy_url.host: + raise InvalidProxyURL( + "Please check proxy URL. It is malformed " + "and could be missing the host." + ) + proxy_manager = self.proxy_manager_for(proxy) + conn = proxy_manager.connection_from_host( + **host_params, pool_kwargs=pool_kwargs + ) + else: + # Only scheme should be lower case + conn = self.poolmanager.connection_from_host( + **host_params, pool_kwargs=pool_kwargs + ) + + return conn + + def get_connection(self, url, proxies=None): + """DEPRECATED: Users should move to `get_connection_with_tls_context` + for all subclasses of HTTPAdapter using Requests>=2.32.2. + + Returns a urllib3 connection for the given URL. This should not be + called from user code, and is only exposed for use when subclassing the + :class:`HTTPAdapter `. + + :param url: The URL to connect to. + :param proxies: (optional) A Requests-style dictionary of proxies used on this request. + :rtype: urllib3.ConnectionPool + """ + warnings.warn( + ( + "`get_connection` has been deprecated in favor of " + "`get_connection_with_tls_context`. Custom HTTPAdapter subclasses " + "will need to migrate for Requests>=2.32.2. Please see " + "https://github.com/psf/requests/pull/6710 for more details." + ), + DeprecationWarning, + ) + proxy = select_proxy(url, proxies) + + if proxy: + proxy = prepend_scheme_if_needed(proxy, "http") + proxy_url = parse_url(proxy) + if not proxy_url.host: + raise InvalidProxyURL( + "Please check proxy URL. It is malformed " + "and could be missing the host." + ) + proxy_manager = self.proxy_manager_for(proxy) + conn = proxy_manager.connection_from_url(url) + else: + # Only scheme should be lower case + parsed = urlparse(url) + url = parsed.geturl() + conn = self.poolmanager.connection_from_url(url) + + return conn + + def close(self): + """Disposes of any internal state. + + Currently, this closes the PoolManager and any active ProxyManager, + which closes any pooled connections. + """ + self.poolmanager.clear() + for proxy in self.proxy_manager.values(): + proxy.clear() + + def request_url(self, request, proxies): + """Obtain the url to use when making the final request. + + If the message is being sent through a HTTP proxy, the full URL has to + be used. Otherwise, we should only use the path portion of the URL. + + This should not be called from user code, and is only exposed for use + when subclassing the + :class:`HTTPAdapter `. + + :param request: The :class:`PreparedRequest ` being sent. + :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs. + :rtype: str + """ + proxy = select_proxy(request.url, proxies) + scheme = urlparse(request.url).scheme + + is_proxied_http_request = proxy and scheme != "https" + using_socks_proxy = False + if proxy: + proxy_scheme = urlparse(proxy).scheme.lower() + using_socks_proxy = proxy_scheme.startswith("socks") + + url = request.path_url + if url.startswith("//"): # Don't confuse urllib3 + url = f"/{url.lstrip('/')}" + + if is_proxied_http_request and not using_socks_proxy: + url = urldefragauth(request.url) + + return url + + def add_headers(self, request, **kwargs): + """Add any headers needed by the connection. As of v2.0 this does + nothing by default, but is left for overriding by users that subclass + the :class:`HTTPAdapter `. + + This should not be called from user code, and is only exposed for use + when subclassing the + :class:`HTTPAdapter `. + + :param request: The :class:`PreparedRequest ` to add headers to. + :param kwargs: The keyword arguments from the call to send(). + """ + pass + + def proxy_headers(self, proxy): + """Returns a dictionary of the headers to add to any request sent + through a proxy. This works with urllib3 magic to ensure that they are + correctly sent to the proxy, rather than in a tunnelled request if + CONNECT is being used. + + This should not be called from user code, and is only exposed for use + when subclassing the + :class:`HTTPAdapter `. + + :param proxy: The url of the proxy being used for this request. + :rtype: dict + """ + headers = {} + username, password = get_auth_from_url(proxy) + + if username: + headers["Proxy-Authorization"] = _basic_auth_str(username, password) + + return headers + + def send( + self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None + ): + """Sends PreparedRequest object. Returns Response object. + + :param request: The :class:`PreparedRequest ` being sent. + :param stream: (optional) Whether to stream the request content. + :param timeout: (optional) How long to wait for the server to send + data before giving up, as a float, or a :ref:`(connect timeout, + read timeout) ` tuple. + :type timeout: float or tuple or urllib3 Timeout object + :param verify: (optional) Either a boolean, in which case it controls whether + we verify the server's TLS certificate, or a string, in which case it + must be a path to a CA bundle to use + :param cert: (optional) Any user-provided SSL certificate to be trusted. + :param proxies: (optional) The proxies dictionary to apply to the request. + :rtype: requests.Response + """ + + try: + conn = self.get_connection_with_tls_context( + request, verify, proxies=proxies, cert=cert + ) + except LocationValueError as e: + raise InvalidURL(e, request=request) + + self.cert_verify(conn, request.url, verify, cert) + url = self.request_url(request, proxies) + self.add_headers( + request, + stream=stream, + timeout=timeout, + verify=verify, + cert=cert, + proxies=proxies, + ) + + chunked = not (request.body is None or "Content-Length" in request.headers) + + if isinstance(timeout, tuple): + try: + connect, read = timeout + timeout = TimeoutSauce(connect=connect, read=read) + except ValueError: + raise ValueError( + f"Invalid timeout {timeout}. Pass a (connect, read) timeout tuple, " + f"or a single float to set both timeouts to the same value." + ) + elif isinstance(timeout, TimeoutSauce): + pass + else: + timeout = TimeoutSauce(connect=timeout, read=timeout) + + try: + resp = conn.urlopen( + method=request.method, + url=url, + body=request.body, + headers=request.headers, + redirect=False, + assert_same_host=False, + preload_content=False, + decode_content=False, + retries=self.max_retries, + timeout=timeout, + chunked=chunked, + ) + + except (ProtocolError, OSError) as err: + raise ConnectionError(err, request=request) + + except MaxRetryError as e: + if isinstance(e.reason, ConnectTimeoutError): + # TODO: Remove this in 3.0.0: see #2811 + if not isinstance(e.reason, NewConnectionError): + raise ConnectTimeout(e, request=request) + + if isinstance(e.reason, ResponseError): + raise RetryError(e, request=request) + + if isinstance(e.reason, _ProxyError): + raise ProxyError(e, request=request) + + if isinstance(e.reason, _SSLError): + # This branch is for urllib3 v1.22 and later. + raise SSLError(e, request=request) + + raise ConnectionError(e, request=request) + + except ClosedPoolError as e: + raise ConnectionError(e, request=request) + + except _ProxyError as e: + raise ProxyError(e) + + except (_SSLError, _HTTPError) as e: + if isinstance(e, _SSLError): + # This branch is for urllib3 versions earlier than v1.22 + raise SSLError(e, request=request) + elif isinstance(e, ReadTimeoutError): + raise ReadTimeout(e, request=request) + elif isinstance(e, _InvalidHeader): + raise InvalidHeader(e, request=request) + else: + raise + + return self.build_response(request, resp) diff --git a/wemm/lib/python3.10/site-packages/requests/api.py b/wemm/lib/python3.10/site-packages/requests/api.py new file mode 100644 index 0000000000000000000000000000000000000000..5960744552e7f8eea815429e7bdad38b0cc2741d --- /dev/null +++ b/wemm/lib/python3.10/site-packages/requests/api.py @@ -0,0 +1,157 @@ +""" +requests.api +~~~~~~~~~~~~ + +This module implements the Requests API. + +:copyright: (c) 2012 by Kenneth Reitz. +:license: Apache2, see LICENSE for more details. +""" + +from . import sessions + + +def request(method, url, **kwargs): + """Constructs and sends a :class:`Request `. + + :param method: method for the new :class:`Request` object: ``GET``, ``OPTIONS``, ``HEAD``, ``POST``, ``PUT``, ``PATCH``, or ``DELETE``. + :param url: URL for the new :class:`Request` object. + :param params: (optional) Dictionary, list of tuples or bytes to send + in the query string for the :class:`Request`. + :param data: (optional) Dictionary, list of tuples, bytes, or file-like + object to send in the body of the :class:`Request`. + :param json: (optional) A JSON serializable Python object to send in the body of the :class:`Request`. + :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`. + :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`. + :param files: (optional) Dictionary of ``'name': file-like-objects`` (or ``{'name': file-tuple}``) for multipart encoding upload. + ``file-tuple`` can be a 2-tuple ``('filename', fileobj)``, 3-tuple ``('filename', fileobj, 'content_type')`` + or a 4-tuple ``('filename', fileobj, 'content_type', custom_headers)``, where ``'content_type'`` is a string + defining the content type of the given file and ``custom_headers`` a dict-like object containing additional headers + to add for the file. + :param auth: (optional) Auth tuple to enable Basic/Digest/Custom HTTP Auth. + :param timeout: (optional) How many seconds to wait for the server to send data + before giving up, as a float, or a :ref:`(connect timeout, read + timeout) ` tuple. + :type timeout: float or tuple + :param allow_redirects: (optional) Boolean. Enable/disable GET/OPTIONS/POST/PUT/PATCH/DELETE/HEAD redirection. Defaults to ``True``. + :type allow_redirects: bool + :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy. + :param verify: (optional) Either a boolean, in which case it controls whether we verify + the server's TLS certificate, or a string, in which case it must be a path + to a CA bundle to use. Defaults to ``True``. + :param stream: (optional) if ``False``, the response content will be immediately downloaded. + :param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair. + :return: :class:`Response ` object + :rtype: requests.Response + + Usage:: + + >>> import requests + >>> req = requests.request('GET', 'https://httpbin.org/get') + >>> req + + """ + + # By using the 'with' statement we are sure the session is closed, thus we + # avoid leaving sockets open which can trigger a ResourceWarning in some + # cases, and look like a memory leak in others. + with sessions.Session() as session: + return session.request(method=method, url=url, **kwargs) + + +def get(url, params=None, **kwargs): + r"""Sends a GET request. + + :param url: URL for the new :class:`Request` object. + :param params: (optional) Dictionary, list of tuples or bytes to send + in the query string for the :class:`Request`. + :param \*\*kwargs: Optional arguments that ``request`` takes. + :return: :class:`Response ` object + :rtype: requests.Response + """ + + return request("get", url, params=params, **kwargs) + + +def options(url, **kwargs): + r"""Sends an OPTIONS request. + + :param url: URL for the new :class:`Request` object. + :param \*\*kwargs: Optional arguments that ``request`` takes. + :return: :class:`Response ` object + :rtype: requests.Response + """ + + return request("options", url, **kwargs) + + +def head(url, **kwargs): + r"""Sends a HEAD request. + + :param url: URL for the new :class:`Request` object. + :param \*\*kwargs: Optional arguments that ``request`` takes. If + `allow_redirects` is not provided, it will be set to `False` (as + opposed to the default :meth:`request` behavior). + :return: :class:`Response ` object + :rtype: requests.Response + """ + + kwargs.setdefault("allow_redirects", False) + return request("head", url, **kwargs) + + +def post(url, data=None, json=None, **kwargs): + r"""Sends a POST request. + + :param url: URL for the new :class:`Request` object. + :param data: (optional) Dictionary, list of tuples, bytes, or file-like + object to send in the body of the :class:`Request`. + :param json: (optional) A JSON serializable Python object to send in the body of the :class:`Request`. + :param \*\*kwargs: Optional arguments that ``request`` takes. + :return: :class:`Response ` object + :rtype: requests.Response + """ + + return request("post", url, data=data, json=json, **kwargs) + + +def put(url, data=None, **kwargs): + r"""Sends a PUT request. + + :param url: URL for the new :class:`Request` object. + :param data: (optional) Dictionary, list of tuples, bytes, or file-like + object to send in the body of the :class:`Request`. + :param json: (optional) A JSON serializable Python object to send in the body of the :class:`Request`. + :param \*\*kwargs: Optional arguments that ``request`` takes. + :return: :class:`Response ` object + :rtype: requests.Response + """ + + return request("put", url, data=data, **kwargs) + + +def patch(url, data=None, **kwargs): + r"""Sends a PATCH request. + + :param url: URL for the new :class:`Request` object. + :param data: (optional) Dictionary, list of tuples, bytes, or file-like + object to send in the body of the :class:`Request`. + :param json: (optional) A JSON serializable Python object to send in the body of the :class:`Request`. + :param \*\*kwargs: Optional arguments that ``request`` takes. + :return: :class:`Response ` object + :rtype: requests.Response + """ + + return request("patch", url, data=data, **kwargs) + + +def delete(url, **kwargs): + r"""Sends a DELETE request. + + :param url: URL for the new :class:`Request` object. + :param \*\*kwargs: Optional arguments that ``request`` takes. + :return: :class:`Response ` object + :rtype: requests.Response + """ + + return request("delete", url, **kwargs) diff --git a/wemm/lib/python3.10/site-packages/requests/auth.py b/wemm/lib/python3.10/site-packages/requests/auth.py new file mode 100644 index 0000000000000000000000000000000000000000..4a7ce6dc1460e0de8aa0c38ea9123faa69bd5110 --- /dev/null +++ b/wemm/lib/python3.10/site-packages/requests/auth.py @@ -0,0 +1,314 @@ +""" +requests.auth +~~~~~~~~~~~~~ + +This module contains the authentication handlers for Requests. +""" + +import hashlib +import os +import re +import threading +import time +import warnings +from base64 import b64encode + +from ._internal_utils import to_native_string +from .compat import basestring, str, urlparse +from .cookies import extract_cookies_to_jar +from .utils import parse_dict_header + +CONTENT_TYPE_FORM_URLENCODED = "application/x-www-form-urlencoded" +CONTENT_TYPE_MULTI_PART = "multipart/form-data" + + +def _basic_auth_str(username, password): + """Returns a Basic Auth string.""" + + # "I want us to put a big-ol' comment on top of it that + # says that this behaviour is dumb but we need to preserve + # it because people are relying on it." + # - Lukasa + # + # These are here solely to maintain backwards compatibility + # for things like ints. This will be removed in 3.0.0. + if not isinstance(username, basestring): + warnings.warn( + "Non-string usernames will no longer be supported in Requests " + "3.0.0. Please convert the object you've passed in ({!r}) to " + "a string or bytes object in the near future to avoid " + "problems.".format(username), + category=DeprecationWarning, + ) + username = str(username) + + if not isinstance(password, basestring): + warnings.warn( + "Non-string passwords will no longer be supported in Requests " + "3.0.0. Please convert the object you've passed in ({!r}) to " + "a string or bytes object in the near future to avoid " + "problems.".format(type(password)), + category=DeprecationWarning, + ) + password = str(password) + # -- End Removal -- + + if isinstance(username, str): + username = username.encode("latin1") + + if isinstance(password, str): + password = password.encode("latin1") + + authstr = "Basic " + to_native_string( + b64encode(b":".join((username, password))).strip() + ) + + return authstr + + +class AuthBase: + """Base class that all auth implementations derive from""" + + def __call__(self, r): + raise NotImplementedError("Auth hooks must be callable.") + + +class HTTPBasicAuth(AuthBase): + """Attaches HTTP Basic Authentication to the given Request object.""" + + def __init__(self, username, password): + self.username = username + self.password = password + + def __eq__(self, other): + return all( + [ + self.username == getattr(other, "username", None), + self.password == getattr(other, "password", None), + ] + ) + + def __ne__(self, other): + return not self == other + + def __call__(self, r): + r.headers["Authorization"] = _basic_auth_str(self.username, self.password) + return r + + +class HTTPProxyAuth(HTTPBasicAuth): + """Attaches HTTP Proxy Authentication to a given Request object.""" + + def __call__(self, r): + r.headers["Proxy-Authorization"] = _basic_auth_str(self.username, self.password) + return r + + +class HTTPDigestAuth(AuthBase): + """Attaches HTTP Digest Authentication to the given Request object.""" + + def __init__(self, username, password): + self.username = username + self.password = password + # Keep state in per-thread local storage + self._thread_local = threading.local() + + def init_per_thread_state(self): + # Ensure state is initialized just once per-thread + if not hasattr(self._thread_local, "init"): + self._thread_local.init = True + self._thread_local.last_nonce = "" + self._thread_local.nonce_count = 0 + self._thread_local.chal = {} + self._thread_local.pos = None + self._thread_local.num_401_calls = None + + def build_digest_header(self, method, url): + """ + :rtype: str + """ + + realm = self._thread_local.chal["realm"] + nonce = self._thread_local.chal["nonce"] + qop = self._thread_local.chal.get("qop") + algorithm = self._thread_local.chal.get("algorithm") + opaque = self._thread_local.chal.get("opaque") + hash_utf8 = None + + if algorithm is None: + _algorithm = "MD5" + else: + _algorithm = algorithm.upper() + # lambdas assume digest modules are imported at the top level + if _algorithm == "MD5" or _algorithm == "MD5-SESS": + + def md5_utf8(x): + if isinstance(x, str): + x = x.encode("utf-8") + return hashlib.md5(x).hexdigest() + + hash_utf8 = md5_utf8 + elif _algorithm == "SHA": + + def sha_utf8(x): + if isinstance(x, str): + x = x.encode("utf-8") + return hashlib.sha1(x).hexdigest() + + hash_utf8 = sha_utf8 + elif _algorithm == "SHA-256": + + def sha256_utf8(x): + if isinstance(x, str): + x = x.encode("utf-8") + return hashlib.sha256(x).hexdigest() + + hash_utf8 = sha256_utf8 + elif _algorithm == "SHA-512": + + def sha512_utf8(x): + if isinstance(x, str): + x = x.encode("utf-8") + return hashlib.sha512(x).hexdigest() + + hash_utf8 = sha512_utf8 + + KD = lambda s, d: hash_utf8(f"{s}:{d}") # noqa:E731 + + if hash_utf8 is None: + return None + + # XXX not implemented yet + entdig = None + p_parsed = urlparse(url) + #: path is request-uri defined in RFC 2616 which should not be empty + path = p_parsed.path or "/" + if p_parsed.query: + path += f"?{p_parsed.query}" + + A1 = f"{self.username}:{realm}:{self.password}" + A2 = f"{method}:{path}" + + HA1 = hash_utf8(A1) + HA2 = hash_utf8(A2) + + if nonce == self._thread_local.last_nonce: + self._thread_local.nonce_count += 1 + else: + self._thread_local.nonce_count = 1 + ncvalue = f"{self._thread_local.nonce_count:08x}" + s = str(self._thread_local.nonce_count).encode("utf-8") + s += nonce.encode("utf-8") + s += time.ctime().encode("utf-8") + s += os.urandom(8) + + cnonce = hashlib.sha1(s).hexdigest()[:16] + if _algorithm == "MD5-SESS": + HA1 = hash_utf8(f"{HA1}:{nonce}:{cnonce}") + + if not qop: + respdig = KD(HA1, f"{nonce}:{HA2}") + elif qop == "auth" or "auth" in qop.split(","): + noncebit = f"{nonce}:{ncvalue}:{cnonce}:auth:{HA2}" + respdig = KD(HA1, noncebit) + else: + # XXX handle auth-int. + return None + + self._thread_local.last_nonce = nonce + + # XXX should the partial digests be encoded too? + base = ( + f'username="{self.username}", realm="{realm}", nonce="{nonce}", ' + f'uri="{path}", response="{respdig}"' + ) + if opaque: + base += f', opaque="{opaque}"' + if algorithm: + base += f', algorithm="{algorithm}"' + if entdig: + base += f', digest="{entdig}"' + if qop: + base += f', qop="auth", nc={ncvalue}, cnonce="{cnonce}"' + + return f"Digest {base}" + + def handle_redirect(self, r, **kwargs): + """Reset num_401_calls counter on redirects.""" + if r.is_redirect: + self._thread_local.num_401_calls = 1 + + def handle_401(self, r, **kwargs): + """ + Takes the given response and tries digest-auth, if needed. + + :rtype: requests.Response + """ + + # If response is not 4xx, do not auth + # See https://github.com/psf/requests/issues/3772 + if not 400 <= r.status_code < 500: + self._thread_local.num_401_calls = 1 + return r + + if self._thread_local.pos is not None: + # Rewind the file position indicator of the body to where + # it was to resend the request. + r.request.body.seek(self._thread_local.pos) + s_auth = r.headers.get("www-authenticate", "") + + if "digest" in s_auth.lower() and self._thread_local.num_401_calls < 2: + self._thread_local.num_401_calls += 1 + pat = re.compile(r"digest ", flags=re.IGNORECASE) + self._thread_local.chal = parse_dict_header(pat.sub("", s_auth, count=1)) + + # Consume content and release the original connection + # to allow our new request to reuse the same one. + r.content + r.close() + prep = r.request.copy() + extract_cookies_to_jar(prep._cookies, r.request, r.raw) + prep.prepare_cookies(prep._cookies) + + prep.headers["Authorization"] = self.build_digest_header( + prep.method, prep.url + ) + _r = r.connection.send(prep, **kwargs) + _r.history.append(r) + _r.request = prep + + return _r + + self._thread_local.num_401_calls = 1 + return r + + def __call__(self, r): + # Initialize per-thread state, if needed + self.init_per_thread_state() + # If we have a saved nonce, skip the 401 + if self._thread_local.last_nonce: + r.headers["Authorization"] = self.build_digest_header(r.method, r.url) + try: + self._thread_local.pos = r.body.tell() + except AttributeError: + # In the case of HTTPDigestAuth being reused and the body of + # the previous request was a file-like object, pos has the + # file position of the previous body. Ensure it's set to + # None. + self._thread_local.pos = None + r.register_hook("response", self.handle_401) + r.register_hook("response", self.handle_redirect) + self._thread_local.num_401_calls = 1 + + return r + + def __eq__(self, other): + return all( + [ + self.username == getattr(other, "username", None), + self.password == getattr(other, "password", None), + ] + ) + + def __ne__(self, other): + return not self == other diff --git a/wemm/lib/python3.10/site-packages/requests/compat.py b/wemm/lib/python3.10/site-packages/requests/compat.py new file mode 100644 index 0000000000000000000000000000000000000000..095de1b6cae2f460174af54efa975411645f40c6 --- /dev/null +++ b/wemm/lib/python3.10/site-packages/requests/compat.py @@ -0,0 +1,94 @@ +""" +requests.compat +~~~~~~~~~~~~~~~ + +This module previously handled import compatibility issues +between Python 2 and Python 3. It remains for backwards +compatibility until the next major version. +""" + +import importlib +import sys + +# ------------------- +# Character Detection +# ------------------- + + +def _resolve_char_detection(): + """Find supported character detection libraries.""" + chardet = None + for lib in ("chardet", "charset_normalizer"): + if chardet is None: + try: + chardet = importlib.import_module(lib) + except ImportError: + pass + return chardet + + +chardet = _resolve_char_detection() + +# ------- +# Pythons +# ------- + +# Syntax sugar. +_ver = sys.version_info + +#: Python 2.x? +is_py2 = _ver[0] == 2 + +#: Python 3.x? +is_py3 = _ver[0] == 3 + +# json/simplejson module import resolution +has_simplejson = False +try: + import simplejson as json + + has_simplejson = True +except ImportError: + import json + +if has_simplejson: + from simplejson import JSONDecodeError +else: + from json import JSONDecodeError + +# Keep OrderedDict for backwards compatibility. +from collections import OrderedDict +from collections.abc import Callable, Mapping, MutableMapping +from http import cookiejar as cookielib +from http.cookies import Morsel +from io import StringIO + +# -------------- +# Legacy Imports +# -------------- +from urllib.parse import ( + quote, + quote_plus, + unquote, + unquote_plus, + urldefrag, + urlencode, + urljoin, + urlparse, + urlsplit, + urlunparse, +) +from urllib.request import ( + getproxies, + getproxies_environment, + parse_http_list, + proxy_bypass, + proxy_bypass_environment, +) + +builtin_str = str +str = str +bytes = bytes +basestring = (str, bytes) +numeric_types = (int, float) +integer_types = (int,) diff --git a/wemm/lib/python3.10/site-packages/requests/cookies.py b/wemm/lib/python3.10/site-packages/requests/cookies.py new file mode 100644 index 0000000000000000000000000000000000000000..f69d0cda9e1c893401015a09f2db2de5a5960fd2 --- /dev/null +++ b/wemm/lib/python3.10/site-packages/requests/cookies.py @@ -0,0 +1,561 @@ +""" +requests.cookies +~~~~~~~~~~~~~~~~ + +Compatibility code to be able to use `http.cookiejar.CookieJar` with requests. + +requests.utils imports from here, so be careful with imports. +""" + +import calendar +import copy +import time + +from ._internal_utils import to_native_string +from .compat import Morsel, MutableMapping, cookielib, urlparse, urlunparse + +try: + import threading +except ImportError: + import dummy_threading as threading + + +class MockRequest: + """Wraps a `requests.Request` to mimic a `urllib2.Request`. + + The code in `http.cookiejar.CookieJar` expects this interface in order to correctly + manage cookie policies, i.e., determine whether a cookie can be set, given the + domains of the request and the cookie. + + The original request object is read-only. The client is responsible for collecting + the new headers via `get_new_headers()` and interpreting them appropriately. You + probably want `get_cookie_header`, defined below. + """ + + def __init__(self, request): + self._r = request + self._new_headers = {} + self.type = urlparse(self._r.url).scheme + + def get_type(self): + return self.type + + def get_host(self): + return urlparse(self._r.url).netloc + + def get_origin_req_host(self): + return self.get_host() + + def get_full_url(self): + # Only return the response's URL if the user hadn't set the Host + # header + if not self._r.headers.get("Host"): + return self._r.url + # If they did set it, retrieve it and reconstruct the expected domain + host = to_native_string(self._r.headers["Host"], encoding="utf-8") + parsed = urlparse(self._r.url) + # Reconstruct the URL as we expect it + return urlunparse( + [ + parsed.scheme, + host, + parsed.path, + parsed.params, + parsed.query, + parsed.fragment, + ] + ) + + def is_unverifiable(self): + return True + + def has_header(self, name): + return name in self._r.headers or name in self._new_headers + + def get_header(self, name, default=None): + return self._r.headers.get(name, self._new_headers.get(name, default)) + + def add_header(self, key, val): + """cookiejar has no legitimate use for this method; add it back if you find one.""" + raise NotImplementedError( + "Cookie headers should be added with add_unredirected_header()" + ) + + def add_unredirected_header(self, name, value): + self._new_headers[name] = value + + def get_new_headers(self): + return self._new_headers + + @property + def unverifiable(self): + return self.is_unverifiable() + + @property + def origin_req_host(self): + return self.get_origin_req_host() + + @property + def host(self): + return self.get_host() + + +class MockResponse: + """Wraps a `httplib.HTTPMessage` to mimic a `urllib.addinfourl`. + + ...what? Basically, expose the parsed HTTP headers from the server response + the way `http.cookiejar` expects to see them. + """ + + def __init__(self, headers): + """Make a MockResponse for `cookiejar` to read. + + :param headers: a httplib.HTTPMessage or analogous carrying the headers + """ + self._headers = headers + + def info(self): + return self._headers + + def getheaders(self, name): + self._headers.getheaders(name) + + +def extract_cookies_to_jar(jar, request, response): + """Extract the cookies from the response into a CookieJar. + + :param jar: http.cookiejar.CookieJar (not necessarily a RequestsCookieJar) + :param request: our own requests.Request object + :param response: urllib3.HTTPResponse object + """ + if not (hasattr(response, "_original_response") and response._original_response): + return + # the _original_response field is the wrapped httplib.HTTPResponse object, + req = MockRequest(request) + # pull out the HTTPMessage with the headers and put it in the mock: + res = MockResponse(response._original_response.msg) + jar.extract_cookies(res, req) + + +def get_cookie_header(jar, request): + """ + Produce an appropriate Cookie header string to be sent with `request`, or None. + + :rtype: str + """ + r = MockRequest(request) + jar.add_cookie_header(r) + return r.get_new_headers().get("Cookie") + + +def remove_cookie_by_name(cookiejar, name, domain=None, path=None): + """Unsets a cookie by name, by default over all domains and paths. + + Wraps CookieJar.clear(), is O(n). + """ + clearables = [] + for cookie in cookiejar: + if cookie.name != name: + continue + if domain is not None and domain != cookie.domain: + continue + if path is not None and path != cookie.path: + continue + clearables.append((cookie.domain, cookie.path, cookie.name)) + + for domain, path, name in clearables: + cookiejar.clear(domain, path, name) + + +class CookieConflictError(RuntimeError): + """There are two cookies that meet the criteria specified in the cookie jar. + Use .get and .set and include domain and path args in order to be more specific. + """ + + +class RequestsCookieJar(cookielib.CookieJar, MutableMapping): + """Compatibility class; is a http.cookiejar.CookieJar, but exposes a dict + interface. + + This is the CookieJar we create by default for requests and sessions that + don't specify one, since some clients may expect response.cookies and + session.cookies to support dict operations. + + Requests does not use the dict interface internally; it's just for + compatibility with external client code. All requests code should work + out of the box with externally provided instances of ``CookieJar``, e.g. + ``LWPCookieJar`` and ``FileCookieJar``. + + Unlike a regular CookieJar, this class is pickleable. + + .. warning:: dictionary operations that are normally O(1) may be O(n). + """ + + def get(self, name, default=None, domain=None, path=None): + """Dict-like get() that also supports optional domain and path args in + order to resolve naming collisions from using one cookie jar over + multiple domains. + + .. warning:: operation is O(n), not O(1). + """ + try: + return self._find_no_duplicates(name, domain, path) + except KeyError: + return default + + def set(self, name, value, **kwargs): + """Dict-like set() that also supports optional domain and path args in + order to resolve naming collisions from using one cookie jar over + multiple domains. + """ + # support client code that unsets cookies by assignment of a None value: + if value is None: + remove_cookie_by_name( + self, name, domain=kwargs.get("domain"), path=kwargs.get("path") + ) + return + + if isinstance(value, Morsel): + c = morsel_to_cookie(value) + else: + c = create_cookie(name, value, **kwargs) + self.set_cookie(c) + return c + + def iterkeys(self): + """Dict-like iterkeys() that returns an iterator of names of cookies + from the jar. + + .. seealso:: itervalues() and iteritems(). + """ + for cookie in iter(self): + yield cookie.name + + def keys(self): + """Dict-like keys() that returns a list of names of cookies from the + jar. + + .. seealso:: values() and items(). + """ + return list(self.iterkeys()) + + def itervalues(self): + """Dict-like itervalues() that returns an iterator of values of cookies + from the jar. + + .. seealso:: iterkeys() and iteritems(). + """ + for cookie in iter(self): + yield cookie.value + + def values(self): + """Dict-like values() that returns a list of values of cookies from the + jar. + + .. seealso:: keys() and items(). + """ + return list(self.itervalues()) + + def iteritems(self): + """Dict-like iteritems() that returns an iterator of name-value tuples + from the jar. + + .. seealso:: iterkeys() and itervalues(). + """ + for cookie in iter(self): + yield cookie.name, cookie.value + + def items(self): + """Dict-like items() that returns a list of name-value tuples from the + jar. Allows client-code to call ``dict(RequestsCookieJar)`` and get a + vanilla python dict of key value pairs. + + .. seealso:: keys() and values(). + """ + return list(self.iteritems()) + + def list_domains(self): + """Utility method to list all the domains in the jar.""" + domains = [] + for cookie in iter(self): + if cookie.domain not in domains: + domains.append(cookie.domain) + return domains + + def list_paths(self): + """Utility method to list all the paths in the jar.""" + paths = [] + for cookie in iter(self): + if cookie.path not in paths: + paths.append(cookie.path) + return paths + + def multiple_domains(self): + """Returns True if there are multiple domains in the jar. + Returns False otherwise. + + :rtype: bool + """ + domains = [] + for cookie in iter(self): + if cookie.domain is not None and cookie.domain in domains: + return True + domains.append(cookie.domain) + return False # there is only one domain in jar + + def get_dict(self, domain=None, path=None): + """Takes as an argument an optional domain and path and returns a plain + old Python dict of name-value pairs of cookies that meet the + requirements. + + :rtype: dict + """ + dictionary = {} + for cookie in iter(self): + if (domain is None or cookie.domain == domain) and ( + path is None or cookie.path == path + ): + dictionary[cookie.name] = cookie.value + return dictionary + + def __contains__(self, name): + try: + return super().__contains__(name) + except CookieConflictError: + return True + + def __getitem__(self, name): + """Dict-like __getitem__() for compatibility with client code. Throws + exception if there are more than one cookie with name. In that case, + use the more explicit get() method instead. + + .. warning:: operation is O(n), not O(1). + """ + return self._find_no_duplicates(name) + + def __setitem__(self, name, value): + """Dict-like __setitem__ for compatibility with client code. Throws + exception if there is already a cookie of that name in the jar. In that + case, use the more explicit set() method instead. + """ + self.set(name, value) + + def __delitem__(self, name): + """Deletes a cookie given a name. Wraps ``http.cookiejar.CookieJar``'s + ``remove_cookie_by_name()``. + """ + remove_cookie_by_name(self, name) + + def set_cookie(self, cookie, *args, **kwargs): + if ( + hasattr(cookie.value, "startswith") + and cookie.value.startswith('"') + and cookie.value.endswith('"') + ): + cookie.value = cookie.value.replace('\\"', "") + return super().set_cookie(cookie, *args, **kwargs) + + def update(self, other): + """Updates this jar with cookies from another CookieJar or dict-like""" + if isinstance(other, cookielib.CookieJar): + for cookie in other: + self.set_cookie(copy.copy(cookie)) + else: + super().update(other) + + def _find(self, name, domain=None, path=None): + """Requests uses this method internally to get cookie values. + + If there are conflicting cookies, _find arbitrarily chooses one. + See _find_no_duplicates if you want an exception thrown if there are + conflicting cookies. + + :param name: a string containing name of cookie + :param domain: (optional) string containing domain of cookie + :param path: (optional) string containing path of cookie + :return: cookie.value + """ + for cookie in iter(self): + if cookie.name == name: + if domain is None or cookie.domain == domain: + if path is None or cookie.path == path: + return cookie.value + + raise KeyError(f"name={name!r}, domain={domain!r}, path={path!r}") + + def _find_no_duplicates(self, name, domain=None, path=None): + """Both ``__get_item__`` and ``get`` call this function: it's never + used elsewhere in Requests. + + :param name: a string containing name of cookie + :param domain: (optional) string containing domain of cookie + :param path: (optional) string containing path of cookie + :raises KeyError: if cookie is not found + :raises CookieConflictError: if there are multiple cookies + that match name and optionally domain and path + :return: cookie.value + """ + toReturn = None + for cookie in iter(self): + if cookie.name == name: + if domain is None or cookie.domain == domain: + if path is None or cookie.path == path: + if toReturn is not None: + # if there are multiple cookies that meet passed in criteria + raise CookieConflictError( + f"There are multiple cookies with name, {name!r}" + ) + # we will eventually return this as long as no cookie conflict + toReturn = cookie.value + + if toReturn: + return toReturn + raise KeyError(f"name={name!r}, domain={domain!r}, path={path!r}") + + def __getstate__(self): + """Unlike a normal CookieJar, this class is pickleable.""" + state = self.__dict__.copy() + # remove the unpickleable RLock object + state.pop("_cookies_lock") + return state + + def __setstate__(self, state): + """Unlike a normal CookieJar, this class is pickleable.""" + self.__dict__.update(state) + if "_cookies_lock" not in self.__dict__: + self._cookies_lock = threading.RLock() + + def copy(self): + """Return a copy of this RequestsCookieJar.""" + new_cj = RequestsCookieJar() + new_cj.set_policy(self.get_policy()) + new_cj.update(self) + return new_cj + + def get_policy(self): + """Return the CookiePolicy instance used.""" + return self._policy + + +def _copy_cookie_jar(jar): + if jar is None: + return None + + if hasattr(jar, "copy"): + # We're dealing with an instance of RequestsCookieJar + return jar.copy() + # We're dealing with a generic CookieJar instance + new_jar = copy.copy(jar) + new_jar.clear() + for cookie in jar: + new_jar.set_cookie(copy.copy(cookie)) + return new_jar + + +def create_cookie(name, value, **kwargs): + """Make a cookie from underspecified parameters. + + By default, the pair of `name` and `value` will be set for the domain '' + and sent on every request (this is sometimes called a "supercookie"). + """ + result = { + "version": 0, + "name": name, + "value": value, + "port": None, + "domain": "", + "path": "/", + "secure": False, + "expires": None, + "discard": True, + "comment": None, + "comment_url": None, + "rest": {"HttpOnly": None}, + "rfc2109": False, + } + + badargs = set(kwargs) - set(result) + if badargs: + raise TypeError( + f"create_cookie() got unexpected keyword arguments: {list(badargs)}" + ) + + result.update(kwargs) + result["port_specified"] = bool(result["port"]) + result["domain_specified"] = bool(result["domain"]) + result["domain_initial_dot"] = result["domain"].startswith(".") + result["path_specified"] = bool(result["path"]) + + return cookielib.Cookie(**result) + + +def morsel_to_cookie(morsel): + """Convert a Morsel object into a Cookie containing the one k/v pair.""" + + expires = None + if morsel["max-age"]: + try: + expires = int(time.time() + int(morsel["max-age"])) + except ValueError: + raise TypeError(f"max-age: {morsel['max-age']} must be integer") + elif morsel["expires"]: + time_template = "%a, %d-%b-%Y %H:%M:%S GMT" + expires = calendar.timegm(time.strptime(morsel["expires"], time_template)) + return create_cookie( + comment=morsel["comment"], + comment_url=bool(morsel["comment"]), + discard=False, + domain=morsel["domain"], + expires=expires, + name=morsel.key, + path=morsel["path"], + port=None, + rest={"HttpOnly": morsel["httponly"]}, + rfc2109=False, + secure=bool(morsel["secure"]), + value=morsel.value, + version=morsel["version"] or 0, + ) + + +def cookiejar_from_dict(cookie_dict, cookiejar=None, overwrite=True): + """Returns a CookieJar from a key/value dictionary. + + :param cookie_dict: Dict of key/values to insert into CookieJar. + :param cookiejar: (optional) A cookiejar to add the cookies to. + :param overwrite: (optional) If False, will not replace cookies + already in the jar with new ones. + :rtype: CookieJar + """ + if cookiejar is None: + cookiejar = RequestsCookieJar() + + if cookie_dict is not None: + names_from_jar = [cookie.name for cookie in cookiejar] + for name in cookie_dict: + if overwrite or (name not in names_from_jar): + cookiejar.set_cookie(create_cookie(name, cookie_dict[name])) + + return cookiejar + + +def merge_cookies(cookiejar, cookies): + """Add cookies to cookiejar and returns a merged CookieJar. + + :param cookiejar: CookieJar object to add the cookies to. + :param cookies: Dictionary or CookieJar object to be added. + :rtype: CookieJar + """ + if not isinstance(cookiejar, cookielib.CookieJar): + raise ValueError("You can only merge into CookieJar") + + if isinstance(cookies, dict): + cookiejar = cookiejar_from_dict(cookies, cookiejar=cookiejar, overwrite=False) + elif isinstance(cookies, cookielib.CookieJar): + try: + cookiejar.update(cookies) + except AttributeError: + for cookie_in_jar in cookies: + cookiejar.set_cookie(cookie_in_jar) + + return cookiejar diff --git a/wemm/lib/python3.10/site-packages/requests/exceptions.py b/wemm/lib/python3.10/site-packages/requests/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..83986b489849131efeb7f286b328961205256fd8 --- /dev/null +++ b/wemm/lib/python3.10/site-packages/requests/exceptions.py @@ -0,0 +1,151 @@ +""" +requests.exceptions +~~~~~~~~~~~~~~~~~~~ + +This module contains the set of Requests' exceptions. +""" +from urllib3.exceptions import HTTPError as BaseHTTPError + +from .compat import JSONDecodeError as CompatJSONDecodeError + + +class RequestException(IOError): + """There was an ambiguous exception that occurred while handling your + request. + """ + + def __init__(self, *args, **kwargs): + """Initialize RequestException with `request` and `response` objects.""" + response = kwargs.pop("response", None) + self.response = response + self.request = kwargs.pop("request", None) + if response is not None and not self.request and hasattr(response, "request"): + self.request = self.response.request + super().__init__(*args, **kwargs) + + +class InvalidJSONError(RequestException): + """A JSON error occurred.""" + + +class JSONDecodeError(InvalidJSONError, CompatJSONDecodeError): + """Couldn't decode the text into json""" + + def __init__(self, *args, **kwargs): + """ + Construct the JSONDecodeError instance first with all + args. Then use it's args to construct the IOError so that + the json specific args aren't used as IOError specific args + and the error message from JSONDecodeError is preserved. + """ + CompatJSONDecodeError.__init__(self, *args) + InvalidJSONError.__init__(self, *self.args, **kwargs) + + def __reduce__(self): + """ + The __reduce__ method called when pickling the object must + be the one from the JSONDecodeError (be it json/simplejson) + as it expects all the arguments for instantiation, not just + one like the IOError, and the MRO would by default call the + __reduce__ method from the IOError due to the inheritance order. + """ + return CompatJSONDecodeError.__reduce__(self) + + +class HTTPError(RequestException): + """An HTTP error occurred.""" + + +class ConnectionError(RequestException): + """A Connection error occurred.""" + + +class ProxyError(ConnectionError): + """A proxy error occurred.""" + + +class SSLError(ConnectionError): + """An SSL error occurred.""" + + +class Timeout(RequestException): + """The request timed out. + + Catching this error will catch both + :exc:`~requests.exceptions.ConnectTimeout` and + :exc:`~requests.exceptions.ReadTimeout` errors. + """ + + +class ConnectTimeout(ConnectionError, Timeout): + """The request timed out while trying to connect to the remote server. + + Requests that produced this error are safe to retry. + """ + + +class ReadTimeout(Timeout): + """The server did not send any data in the allotted amount of time.""" + + +class URLRequired(RequestException): + """A valid URL is required to make a request.""" + + +class TooManyRedirects(RequestException): + """Too many redirects.""" + + +class MissingSchema(RequestException, ValueError): + """The URL scheme (e.g. http or https) is missing.""" + + +class InvalidSchema(RequestException, ValueError): + """The URL scheme provided is either invalid or unsupported.""" + + +class InvalidURL(RequestException, ValueError): + """The URL provided was somehow invalid.""" + + +class InvalidHeader(RequestException, ValueError): + """The header value provided was somehow invalid.""" + + +class InvalidProxyURL(InvalidURL): + """The proxy URL provided is invalid.""" + + +class ChunkedEncodingError(RequestException): + """The server declared chunked encoding but sent an invalid chunk.""" + + +class ContentDecodingError(RequestException, BaseHTTPError): + """Failed to decode response content.""" + + +class StreamConsumedError(RequestException, TypeError): + """The content for this response was already consumed.""" + + +class RetryError(RequestException): + """Custom retries logic failed""" + + +class UnrewindableBodyError(RequestException): + """Requests encountered an error when trying to rewind a body.""" + + +# Warnings + + +class RequestsWarning(Warning): + """Base warning for Requests.""" + + +class FileModeWarning(RequestsWarning, DeprecationWarning): + """A file was opened in text mode, but Requests determined its binary length.""" + + +class RequestsDependencyWarning(RequestsWarning): + """An imported dependency doesn't match the expected version range.""" diff --git a/wemm/lib/python3.10/site-packages/requests/help.py b/wemm/lib/python3.10/site-packages/requests/help.py new file mode 100644 index 0000000000000000000000000000000000000000..8fbcd6560a8fe2c8a07e3bd1441a81e0db9cb689 --- /dev/null +++ b/wemm/lib/python3.10/site-packages/requests/help.py @@ -0,0 +1,134 @@ +"""Module containing bug report helper(s).""" + +import json +import platform +import ssl +import sys + +import idna +import urllib3 + +from . import __version__ as requests_version + +try: + import charset_normalizer +except ImportError: + charset_normalizer = None + +try: + import chardet +except ImportError: + chardet = None + +try: + from urllib3.contrib import pyopenssl +except ImportError: + pyopenssl = None + OpenSSL = None + cryptography = None +else: + import cryptography + import OpenSSL + + +def _implementation(): + """Return a dict with the Python implementation and version. + + Provide both the name and the version of the Python implementation + currently running. For example, on CPython 3.10.3 it will return + {'name': 'CPython', 'version': '3.10.3'}. + + This function works best on CPython and PyPy: in particular, it probably + doesn't work for Jython or IronPython. Future investigation should be done + to work out the correct shape of the code for those platforms. + """ + implementation = platform.python_implementation() + + if implementation == "CPython": + implementation_version = platform.python_version() + elif implementation == "PyPy": + implementation_version = "{}.{}.{}".format( + sys.pypy_version_info.major, + sys.pypy_version_info.minor, + sys.pypy_version_info.micro, + ) + if sys.pypy_version_info.releaselevel != "final": + implementation_version = "".join( + [implementation_version, sys.pypy_version_info.releaselevel] + ) + elif implementation == "Jython": + implementation_version = platform.python_version() # Complete Guess + elif implementation == "IronPython": + implementation_version = platform.python_version() # Complete Guess + else: + implementation_version = "Unknown" + + return {"name": implementation, "version": implementation_version} + + +def info(): + """Generate information for a bug report.""" + try: + platform_info = { + "system": platform.system(), + "release": platform.release(), + } + except OSError: + platform_info = { + "system": "Unknown", + "release": "Unknown", + } + + implementation_info = _implementation() + urllib3_info = {"version": urllib3.__version__} + charset_normalizer_info = {"version": None} + chardet_info = {"version": None} + if charset_normalizer: + charset_normalizer_info = {"version": charset_normalizer.__version__} + if chardet: + chardet_info = {"version": chardet.__version__} + + pyopenssl_info = { + "version": None, + "openssl_version": "", + } + if OpenSSL: + pyopenssl_info = { + "version": OpenSSL.__version__, + "openssl_version": f"{OpenSSL.SSL.OPENSSL_VERSION_NUMBER:x}", + } + cryptography_info = { + "version": getattr(cryptography, "__version__", ""), + } + idna_info = { + "version": getattr(idna, "__version__", ""), + } + + system_ssl = ssl.OPENSSL_VERSION_NUMBER + system_ssl_info = {"version": f"{system_ssl:x}" if system_ssl is not None else ""} + + return { + "platform": platform_info, + "implementation": implementation_info, + "system_ssl": system_ssl_info, + "using_pyopenssl": pyopenssl is not None, + "using_charset_normalizer": chardet is None, + "pyOpenSSL": pyopenssl_info, + "urllib3": urllib3_info, + "chardet": chardet_info, + "charset_normalizer": charset_normalizer_info, + "cryptography": cryptography_info, + "idna": idna_info, + "requests": { + "version": requests_version, + }, + } + + +def main(): + """Pretty-print the bug information as JSON.""" + print(json.dumps(info(), sort_keys=True, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/wemm/lib/python3.10/site-packages/requests/hooks.py b/wemm/lib/python3.10/site-packages/requests/hooks.py new file mode 100644 index 0000000000000000000000000000000000000000..d181ba2ec2e55d274897315887b78fbdca757da8 --- /dev/null +++ b/wemm/lib/python3.10/site-packages/requests/hooks.py @@ -0,0 +1,33 @@ +""" +requests.hooks +~~~~~~~~~~~~~~ + +This module provides the capabilities for the Requests hooks system. + +Available hooks: + +``response``: + The response generated from a Request. +""" +HOOKS = ["response"] + + +def default_hooks(): + return {event: [] for event in HOOKS} + + +# TODO: response is the only one + + +def dispatch_hook(key, hooks, hook_data, **kwargs): + """Dispatches a hook dictionary on a given piece of data.""" + hooks = hooks or {} + hooks = hooks.get(key) + if hooks: + if hasattr(hooks, "__call__"): + hooks = [hooks] + for hook in hooks: + _hook_data = hook(hook_data, **kwargs) + if _hook_data is not None: + hook_data = _hook_data + return hook_data diff --git a/wemm/lib/python3.10/site-packages/requests/models.py b/wemm/lib/python3.10/site-packages/requests/models.py new file mode 100644 index 0000000000000000000000000000000000000000..8f56ca7d23a9a12084df80cb649e019572308cfe --- /dev/null +++ b/wemm/lib/python3.10/site-packages/requests/models.py @@ -0,0 +1,1037 @@ +""" +requests.models +~~~~~~~~~~~~~~~ + +This module contains the primary objects that power Requests. +""" + +import datetime + +# Import encoding now, to avoid implicit import later. +# Implicit import within threads may cause LookupError when standard library is in a ZIP, +# such as in Embedded Python. See https://github.com/psf/requests/issues/3578. +import encodings.idna # noqa: F401 +from io import UnsupportedOperation + +from urllib3.exceptions import ( + DecodeError, + LocationParseError, + ProtocolError, + ReadTimeoutError, + SSLError, +) +from urllib3.fields import RequestField +from urllib3.filepost import encode_multipart_formdata +from urllib3.util import parse_url + +from ._internal_utils import to_native_string, unicode_is_ascii +from .auth import HTTPBasicAuth +from .compat import ( + Callable, + JSONDecodeError, + Mapping, + basestring, + builtin_str, + chardet, + cookielib, +) +from .compat import json as complexjson +from .compat import urlencode, urlsplit, urlunparse +from .cookies import _copy_cookie_jar, cookiejar_from_dict, get_cookie_header +from .exceptions import ( + ChunkedEncodingError, + ConnectionError, + ContentDecodingError, + HTTPError, + InvalidJSONError, + InvalidURL, +) +from .exceptions import JSONDecodeError as RequestsJSONDecodeError +from .exceptions import MissingSchema +from .exceptions import SSLError as RequestsSSLError +from .exceptions import StreamConsumedError +from .hooks import default_hooks +from .status_codes import codes +from .structures import CaseInsensitiveDict +from .utils import ( + check_header_validity, + get_auth_from_url, + guess_filename, + guess_json_utf, + iter_slices, + parse_header_links, + requote_uri, + stream_decode_response_unicode, + super_len, + to_key_val_list, +) + +#: The set of HTTP status codes that indicate an automatically +#: processable redirect. +REDIRECT_STATI = ( + codes.moved, # 301 + codes.found, # 302 + codes.other, # 303 + codes.temporary_redirect, # 307 + codes.permanent_redirect, # 308 +) + +DEFAULT_REDIRECT_LIMIT = 30 +CONTENT_CHUNK_SIZE = 10 * 1024 +ITER_CHUNK_SIZE = 512 + + +class RequestEncodingMixin: + @property + def path_url(self): + """Build the path URL to use.""" + + url = [] + + p = urlsplit(self.url) + + path = p.path + if not path: + path = "/" + + url.append(path) + + query = p.query + if query: + url.append("?") + url.append(query) + + return "".join(url) + + @staticmethod + def _encode_params(data): + """Encode parameters in a piece of data. + + Will successfully encode parameters when passed as a dict or a list of + 2-tuples. Order is retained if data is a list of 2-tuples but arbitrary + if parameters are supplied as a dict. + """ + + if isinstance(data, (str, bytes)): + return data + elif hasattr(data, "read"): + return data + elif hasattr(data, "__iter__"): + result = [] + for k, vs in to_key_val_list(data): + if isinstance(vs, basestring) or not hasattr(vs, "__iter__"): + vs = [vs] + for v in vs: + if v is not None: + result.append( + ( + k.encode("utf-8") if isinstance(k, str) else k, + v.encode("utf-8") if isinstance(v, str) else v, + ) + ) + return urlencode(result, doseq=True) + else: + return data + + @staticmethod + def _encode_files(files, data): + """Build the body for a multipart/form-data request. + + Will successfully encode files when passed as a dict or a list of + tuples. Order is retained if data is a list of tuples but arbitrary + if parameters are supplied as a dict. + The tuples may be 2-tuples (filename, fileobj), 3-tuples (filename, fileobj, contentype) + or 4-tuples (filename, fileobj, contentype, custom_headers). + """ + if not files: + raise ValueError("Files must be provided.") + elif isinstance(data, basestring): + raise ValueError("Data must not be a string.") + + new_fields = [] + fields = to_key_val_list(data or {}) + files = to_key_val_list(files or {}) + + for field, val in fields: + if isinstance(val, basestring) or not hasattr(val, "__iter__"): + val = [val] + for v in val: + if v is not None: + # Don't call str() on bytestrings: in Py3 it all goes wrong. + if not isinstance(v, bytes): + v = str(v) + + new_fields.append( + ( + field.decode("utf-8") + if isinstance(field, bytes) + else field, + v.encode("utf-8") if isinstance(v, str) else v, + ) + ) + + for k, v in files: + # support for explicit filename + ft = None + fh = None + if isinstance(v, (tuple, list)): + if len(v) == 2: + fn, fp = v + elif len(v) == 3: + fn, fp, ft = v + else: + fn, fp, ft, fh = v + else: + fn = guess_filename(v) or k + fp = v + + if isinstance(fp, (str, bytes, bytearray)): + fdata = fp + elif hasattr(fp, "read"): + fdata = fp.read() + elif fp is None: + continue + else: + fdata = fp + + rf = RequestField(name=k, data=fdata, filename=fn, headers=fh) + rf.make_multipart(content_type=ft) + new_fields.append(rf) + + body, content_type = encode_multipart_formdata(new_fields) + + return body, content_type + + +class RequestHooksMixin: + def register_hook(self, event, hook): + """Properly register a hook.""" + + if event not in self.hooks: + raise ValueError(f'Unsupported event specified, with event name "{event}"') + + if isinstance(hook, Callable): + self.hooks[event].append(hook) + elif hasattr(hook, "__iter__"): + self.hooks[event].extend(h for h in hook if isinstance(h, Callable)) + + def deregister_hook(self, event, hook): + """Deregister a previously registered hook. + Returns True if the hook existed, False if not. + """ + + try: + self.hooks[event].remove(hook) + return True + except ValueError: + return False + + +class Request(RequestHooksMixin): + """A user-created :class:`Request ` object. + + Used to prepare a :class:`PreparedRequest `, which is sent to the server. + + :param method: HTTP method to use. + :param url: URL to send. + :param headers: dictionary of headers to send. + :param files: dictionary of {filename: fileobject} files to multipart upload. + :param data: the body to attach to the request. If a dictionary or + list of tuples ``[(key, value)]`` is provided, form-encoding will + take place. + :param json: json for the body to attach to the request (if files or data is not specified). + :param params: URL parameters to append to the URL. If a dictionary or + list of tuples ``[(key, value)]`` is provided, form-encoding will + take place. + :param auth: Auth handler or (user, pass) tuple. + :param cookies: dictionary or CookieJar of cookies to attach to this request. + :param hooks: dictionary of callback hooks, for internal usage. + + Usage:: + + >>> import requests + >>> req = requests.Request('GET', 'https://httpbin.org/get') + >>> req.prepare() + + """ + + def __init__( + self, + method=None, + url=None, + headers=None, + files=None, + data=None, + params=None, + auth=None, + cookies=None, + hooks=None, + json=None, + ): + # Default empty dicts for dict params. + data = [] if data is None else data + files = [] if files is None else files + headers = {} if headers is None else headers + params = {} if params is None else params + hooks = {} if hooks is None else hooks + + self.hooks = default_hooks() + for k, v in list(hooks.items()): + self.register_hook(event=k, hook=v) + + self.method = method + self.url = url + self.headers = headers + self.files = files + self.data = data + self.json = json + self.params = params + self.auth = auth + self.cookies = cookies + + def __repr__(self): + return f"" + + def prepare(self): + """Constructs a :class:`PreparedRequest ` for transmission and returns it.""" + p = PreparedRequest() + p.prepare( + method=self.method, + url=self.url, + headers=self.headers, + files=self.files, + data=self.data, + json=self.json, + params=self.params, + auth=self.auth, + cookies=self.cookies, + hooks=self.hooks, + ) + return p + + +class PreparedRequest(RequestEncodingMixin, RequestHooksMixin): + """The fully mutable :class:`PreparedRequest ` object, + containing the exact bytes that will be sent to the server. + + Instances are generated from a :class:`Request ` object, and + should not be instantiated manually; doing so may produce undesirable + effects. + + Usage:: + + >>> import requests + >>> req = requests.Request('GET', 'https://httpbin.org/get') + >>> r = req.prepare() + >>> r + + + >>> s = requests.Session() + >>> s.send(r) + + """ + + def __init__(self): + #: HTTP verb to send to the server. + self.method = None + #: HTTP URL to send the request to. + self.url = None + #: dictionary of HTTP headers. + self.headers = None + # The `CookieJar` used to create the Cookie header will be stored here + # after prepare_cookies is called + self._cookies = None + #: request body to send to the server. + self.body = None + #: dictionary of callback hooks, for internal usage. + self.hooks = default_hooks() + #: integer denoting starting position of a readable file-like body. + self._body_position = None + + def prepare( + self, + method=None, + url=None, + headers=None, + files=None, + data=None, + params=None, + auth=None, + cookies=None, + hooks=None, + json=None, + ): + """Prepares the entire request with the given parameters.""" + + self.prepare_method(method) + self.prepare_url(url, params) + self.prepare_headers(headers) + self.prepare_cookies(cookies) + self.prepare_body(data, files, json) + self.prepare_auth(auth, url) + + # Note that prepare_auth must be last to enable authentication schemes + # such as OAuth to work on a fully prepared request. + + # This MUST go after prepare_auth. Authenticators could add a hook + self.prepare_hooks(hooks) + + def __repr__(self): + return f"" + + def copy(self): + p = PreparedRequest() + p.method = self.method + p.url = self.url + p.headers = self.headers.copy() if self.headers is not None else None + p._cookies = _copy_cookie_jar(self._cookies) + p.body = self.body + p.hooks = self.hooks + p._body_position = self._body_position + return p + + def prepare_method(self, method): + """Prepares the given HTTP method.""" + self.method = method + if self.method is not None: + self.method = to_native_string(self.method.upper()) + + @staticmethod + def _get_idna_encoded_host(host): + import idna + + try: + host = idna.encode(host, uts46=True).decode("utf-8") + except idna.IDNAError: + raise UnicodeError + return host + + def prepare_url(self, url, params): + """Prepares the given HTTP URL.""" + #: Accept objects that have string representations. + #: We're unable to blindly call unicode/str functions + #: as this will include the bytestring indicator (b'') + #: on python 3.x. + #: https://github.com/psf/requests/pull/2238 + if isinstance(url, bytes): + url = url.decode("utf8") + else: + url = str(url) + + # Remove leading whitespaces from url + url = url.lstrip() + + # Don't do any URL preparation for non-HTTP schemes like `mailto`, + # `data` etc to work around exceptions from `url_parse`, which + # handles RFC 3986 only. + if ":" in url and not url.lower().startswith("http"): + self.url = url + return + + # Support for unicode domain names and paths. + try: + scheme, auth, host, port, path, query, fragment = parse_url(url) + except LocationParseError as e: + raise InvalidURL(*e.args) + + if not scheme: + raise MissingSchema( + f"Invalid URL {url!r}: No scheme supplied. " + f"Perhaps you meant https://{url}?" + ) + + if not host: + raise InvalidURL(f"Invalid URL {url!r}: No host supplied") + + # In general, we want to try IDNA encoding the hostname if the string contains + # non-ASCII characters. This allows users to automatically get the correct IDNA + # behaviour. For strings containing only ASCII characters, we need to also verify + # it doesn't start with a wildcard (*), before allowing the unencoded hostname. + if not unicode_is_ascii(host): + try: + host = self._get_idna_encoded_host(host) + except UnicodeError: + raise InvalidURL("URL has an invalid label.") + elif host.startswith(("*", ".")): + raise InvalidURL("URL has an invalid label.") + + # Carefully reconstruct the network location + netloc = auth or "" + if netloc: + netloc += "@" + netloc += host + if port: + netloc += f":{port}" + + # Bare domains aren't valid URLs. + if not path: + path = "/" + + if isinstance(params, (str, bytes)): + params = to_native_string(params) + + enc_params = self._encode_params(params) + if enc_params: + if query: + query = f"{query}&{enc_params}" + else: + query = enc_params + + url = requote_uri(urlunparse([scheme, netloc, path, None, query, fragment])) + self.url = url + + def prepare_headers(self, headers): + """Prepares the given HTTP headers.""" + + self.headers = CaseInsensitiveDict() + if headers: + for header in headers.items(): + # Raise exception on invalid header value. + check_header_validity(header) + name, value = header + self.headers[to_native_string(name)] = value + + def prepare_body(self, data, files, json=None): + """Prepares the given HTTP body data.""" + + # Check if file, fo, generator, iterator. + # If not, run through normal process. + + # Nottin' on you. + body = None + content_type = None + + if not data and json is not None: + # urllib3 requires a bytes-like body. Python 2's json.dumps + # provides this natively, but Python 3 gives a Unicode string. + content_type = "application/json" + + try: + body = complexjson.dumps(json, allow_nan=False) + except ValueError as ve: + raise InvalidJSONError(ve, request=self) + + if not isinstance(body, bytes): + body = body.encode("utf-8") + + is_stream = all( + [ + hasattr(data, "__iter__"), + not isinstance(data, (basestring, list, tuple, Mapping)), + ] + ) + + if is_stream: + try: + length = super_len(data) + except (TypeError, AttributeError, UnsupportedOperation): + length = None + + body = data + + if getattr(body, "tell", None) is not None: + # Record the current file position before reading. + # This will allow us to rewind a file in the event + # of a redirect. + try: + self._body_position = body.tell() + except OSError: + # This differentiates from None, allowing us to catch + # a failed `tell()` later when trying to rewind the body + self._body_position = object() + + if files: + raise NotImplementedError( + "Streamed bodies and files are mutually exclusive." + ) + + if length: + self.headers["Content-Length"] = builtin_str(length) + else: + self.headers["Transfer-Encoding"] = "chunked" + else: + # Multi-part file uploads. + if files: + (body, content_type) = self._encode_files(files, data) + else: + if data: + body = self._encode_params(data) + if isinstance(data, basestring) or hasattr(data, "read"): + content_type = None + else: + content_type = "application/x-www-form-urlencoded" + + self.prepare_content_length(body) + + # Add content-type if it wasn't explicitly provided. + if content_type and ("content-type" not in self.headers): + self.headers["Content-Type"] = content_type + + self.body = body + + def prepare_content_length(self, body): + """Prepare Content-Length header based on request method and body""" + if body is not None: + length = super_len(body) + if length: + # If length exists, set it. Otherwise, we fallback + # to Transfer-Encoding: chunked. + self.headers["Content-Length"] = builtin_str(length) + elif ( + self.method not in ("GET", "HEAD") + and self.headers.get("Content-Length") is None + ): + # Set Content-Length to 0 for methods that can have a body + # but don't provide one. (i.e. not GET or HEAD) + self.headers["Content-Length"] = "0" + + def prepare_auth(self, auth, url=""): + """Prepares the given HTTP auth data.""" + + # If no Auth is explicitly provided, extract it from the URL first. + if auth is None: + url_auth = get_auth_from_url(self.url) + auth = url_auth if any(url_auth) else None + + if auth: + if isinstance(auth, tuple) and len(auth) == 2: + # special-case basic HTTP auth + auth = HTTPBasicAuth(*auth) + + # Allow auth to make its changes. + r = auth(self) + + # Update self to reflect the auth changes. + self.__dict__.update(r.__dict__) + + # Recompute Content-Length + self.prepare_content_length(self.body) + + def prepare_cookies(self, cookies): + """Prepares the given HTTP cookie data. + + This function eventually generates a ``Cookie`` header from the + given cookies using cookielib. Due to cookielib's design, the header + will not be regenerated if it already exists, meaning this function + can only be called once for the life of the + :class:`PreparedRequest ` object. Any subsequent calls + to ``prepare_cookies`` will have no actual effect, unless the "Cookie" + header is removed beforehand. + """ + if isinstance(cookies, cookielib.CookieJar): + self._cookies = cookies + else: + self._cookies = cookiejar_from_dict(cookies) + + cookie_header = get_cookie_header(self._cookies, self) + if cookie_header is not None: + self.headers["Cookie"] = cookie_header + + def prepare_hooks(self, hooks): + """Prepares the given hooks.""" + # hooks can be passed as None to the prepare method and to this + # method. To prevent iterating over None, simply use an empty list + # if hooks is False-y + hooks = hooks or [] + for event in hooks: + self.register_hook(event, hooks[event]) + + +class Response: + """The :class:`Response ` object, which contains a + server's response to an HTTP request. + """ + + __attrs__ = [ + "_content", + "status_code", + "headers", + "url", + "history", + "encoding", + "reason", + "cookies", + "elapsed", + "request", + ] + + def __init__(self): + self._content = False + self._content_consumed = False + self._next = None + + #: Integer Code of responded HTTP Status, e.g. 404 or 200. + self.status_code = None + + #: Case-insensitive Dictionary of Response Headers. + #: For example, ``headers['content-encoding']`` will return the + #: value of a ``'Content-Encoding'`` response header. + self.headers = CaseInsensitiveDict() + + #: File-like object representation of response (for advanced usage). + #: Use of ``raw`` requires that ``stream=True`` be set on the request. + #: This requirement does not apply for use internally to Requests. + self.raw = None + + #: Final URL location of Response. + self.url = None + + #: Encoding to decode with when accessing r.text. + self.encoding = None + + #: A list of :class:`Response ` objects from + #: the history of the Request. Any redirect responses will end + #: up here. The list is sorted from the oldest to the most recent request. + self.history = [] + + #: Textual reason of responded HTTP Status, e.g. "Not Found" or "OK". + self.reason = None + + #: A CookieJar of Cookies the server sent back. + self.cookies = cookiejar_from_dict({}) + + #: The amount of time elapsed between sending the request + #: and the arrival of the response (as a timedelta). + #: This property specifically measures the time taken between sending + #: the first byte of the request and finishing parsing the headers. It + #: is therefore unaffected by consuming the response content or the + #: value of the ``stream`` keyword argument. + self.elapsed = datetime.timedelta(0) + + #: The :class:`PreparedRequest ` object to which this + #: is a response. + self.request = None + + def __enter__(self): + return self + + def __exit__(self, *args): + self.close() + + def __getstate__(self): + # Consume everything; accessing the content attribute makes + # sure the content has been fully read. + if not self._content_consumed: + self.content + + return {attr: getattr(self, attr, None) for attr in self.__attrs__} + + def __setstate__(self, state): + for name, value in state.items(): + setattr(self, name, value) + + # pickled objects do not have .raw + setattr(self, "_content_consumed", True) + setattr(self, "raw", None) + + def __repr__(self): + return f"" + + def __bool__(self): + """Returns True if :attr:`status_code` is less than 400. + + This attribute checks if the status code of the response is between + 400 and 600 to see if there was a client error or a server error. If + the status code, is between 200 and 400, this will return True. This + is **not** a check to see if the response code is ``200 OK``. + """ + return self.ok + + def __nonzero__(self): + """Returns True if :attr:`status_code` is less than 400. + + This attribute checks if the status code of the response is between + 400 and 600 to see if there was a client error or a server error. If + the status code, is between 200 and 400, this will return True. This + is **not** a check to see if the response code is ``200 OK``. + """ + return self.ok + + def __iter__(self): + """Allows you to use a response as an iterator.""" + return self.iter_content(128) + + @property + def ok(self): + """Returns True if :attr:`status_code` is less than 400, False if not. + + This attribute checks if the status code of the response is between + 400 and 600 to see if there was a client error or a server error. If + the status code is between 200 and 400, this will return True. This + is **not** a check to see if the response code is ``200 OK``. + """ + try: + self.raise_for_status() + except HTTPError: + return False + return True + + @property + def is_redirect(self): + """True if this Response is a well-formed HTTP redirect that could have + been processed automatically (by :meth:`Session.resolve_redirects`). + """ + return "location" in self.headers and self.status_code in REDIRECT_STATI + + @property + def is_permanent_redirect(self): + """True if this Response one of the permanent versions of redirect.""" + return "location" in self.headers and self.status_code in ( + codes.moved_permanently, + codes.permanent_redirect, + ) + + @property + def next(self): + """Returns a PreparedRequest for the next request in a redirect chain, if there is one.""" + return self._next + + @property + def apparent_encoding(self): + """The apparent encoding, provided by the charset_normalizer or chardet libraries.""" + if chardet is not None: + return chardet.detect(self.content)["encoding"] + else: + # If no character detection library is available, we'll fall back + # to a standard Python utf-8 str. + return "utf-8" + + def iter_content(self, chunk_size=1, decode_unicode=False): + """Iterates over the response data. When stream=True is set on the + request, this avoids reading the content at once into memory for + large responses. The chunk size is the number of bytes it should + read into memory. This is not necessarily the length of each item + returned as decoding can take place. + + chunk_size must be of type int or None. A value of None will + function differently depending on the value of `stream`. + stream=True will read data as it arrives in whatever size the + chunks are received. If stream=False, data is returned as + a single chunk. + + If decode_unicode is True, content will be decoded using the best + available encoding based on the response. + """ + + def generate(): + # Special case for urllib3. + if hasattr(self.raw, "stream"): + try: + yield from self.raw.stream(chunk_size, decode_content=True) + except ProtocolError as e: + raise ChunkedEncodingError(e) + except DecodeError as e: + raise ContentDecodingError(e) + except ReadTimeoutError as e: + raise ConnectionError(e) + except SSLError as e: + raise RequestsSSLError(e) + else: + # Standard file-like object. + while True: + chunk = self.raw.read(chunk_size) + if not chunk: + break + yield chunk + + self._content_consumed = True + + if self._content_consumed and isinstance(self._content, bool): + raise StreamConsumedError() + elif chunk_size is not None and not isinstance(chunk_size, int): + raise TypeError( + f"chunk_size must be an int, it is instead a {type(chunk_size)}." + ) + # simulate reading small chunks of the content + reused_chunks = iter_slices(self._content, chunk_size) + + stream_chunks = generate() + + chunks = reused_chunks if self._content_consumed else stream_chunks + + if decode_unicode: + chunks = stream_decode_response_unicode(chunks, self) + + return chunks + + def iter_lines( + self, chunk_size=ITER_CHUNK_SIZE, decode_unicode=False, delimiter=None + ): + """Iterates over the response data, one line at a time. When + stream=True is set on the request, this avoids reading the + content at once into memory for large responses. + + .. note:: This method is not reentrant safe. + """ + + pending = None + + for chunk in self.iter_content( + chunk_size=chunk_size, decode_unicode=decode_unicode + ): + if pending is not None: + chunk = pending + chunk + + if delimiter: + lines = chunk.split(delimiter) + else: + lines = chunk.splitlines() + + if lines and lines[-1] and chunk and lines[-1][-1] == chunk[-1]: + pending = lines.pop() + else: + pending = None + + yield from lines + + if pending is not None: + yield pending + + @property + def content(self): + """Content of the response, in bytes.""" + + if self._content is False: + # Read the contents. + if self._content_consumed: + raise RuntimeError("The content for this response was already consumed") + + if self.status_code == 0 or self.raw is None: + self._content = None + else: + self._content = b"".join(self.iter_content(CONTENT_CHUNK_SIZE)) or b"" + + self._content_consumed = True + # don't need to release the connection; that's been handled by urllib3 + # since we exhausted the data. + return self._content + + @property + def text(self): + """Content of the response, in unicode. + + If Response.encoding is None, encoding will be guessed using + ``charset_normalizer`` or ``chardet``. + + The encoding of the response content is determined based solely on HTTP + headers, following RFC 2616 to the letter. If you can take advantage of + non-HTTP knowledge to make a better guess at the encoding, you should + set ``r.encoding`` appropriately before accessing this property. + """ + + # Try charset from content-type + content = None + encoding = self.encoding + + if not self.content: + return "" + + # Fallback to auto-detected encoding. + if self.encoding is None: + encoding = self.apparent_encoding + + # Decode unicode from given encoding. + try: + content = str(self.content, encoding, errors="replace") + except (LookupError, TypeError): + # A LookupError is raised if the encoding was not found which could + # indicate a misspelling or similar mistake. + # + # A TypeError can be raised if encoding is None + # + # So we try blindly encoding. + content = str(self.content, errors="replace") + + return content + + def json(self, **kwargs): + r"""Returns the json-encoded content of a response, if any. + + :param \*\*kwargs: Optional arguments that ``json.loads`` takes. + :raises requests.exceptions.JSONDecodeError: If the response body does not + contain valid json. + """ + + if not self.encoding and self.content and len(self.content) > 3: + # No encoding set. JSON RFC 4627 section 3 states we should expect + # UTF-8, -16 or -32. Detect which one to use; If the detection or + # decoding fails, fall back to `self.text` (using charset_normalizer to make + # a best guess). + encoding = guess_json_utf(self.content) + if encoding is not None: + try: + return complexjson.loads(self.content.decode(encoding), **kwargs) + except UnicodeDecodeError: + # Wrong UTF codec detected; usually because it's not UTF-8 + # but some other 8-bit codec. This is an RFC violation, + # and the server didn't bother to tell us what codec *was* + # used. + pass + except JSONDecodeError as e: + raise RequestsJSONDecodeError(e.msg, e.doc, e.pos) + + try: + return complexjson.loads(self.text, **kwargs) + except JSONDecodeError as e: + # Catch JSON-related errors and raise as requests.JSONDecodeError + # This aliases json.JSONDecodeError and simplejson.JSONDecodeError + raise RequestsJSONDecodeError(e.msg, e.doc, e.pos) + + @property + def links(self): + """Returns the parsed header links of the response, if any.""" + + header = self.headers.get("link") + + resolved_links = {} + + if header: + links = parse_header_links(header) + + for link in links: + key = link.get("rel") or link.get("url") + resolved_links[key] = link + + return resolved_links + + def raise_for_status(self): + """Raises :class:`HTTPError`, if one occurred.""" + + http_error_msg = "" + if isinstance(self.reason, bytes): + # We attempt to decode utf-8 first because some servers + # choose to localize their reason strings. If the string + # isn't utf-8, we fall back to iso-8859-1 for all other + # encodings. (See PR #3538) + try: + reason = self.reason.decode("utf-8") + except UnicodeDecodeError: + reason = self.reason.decode("iso-8859-1") + else: + reason = self.reason + + if 400 <= self.status_code < 500: + http_error_msg = ( + f"{self.status_code} Client Error: {reason} for url: {self.url}" + ) + + elif 500 <= self.status_code < 600: + http_error_msg = ( + f"{self.status_code} Server Error: {reason} for url: {self.url}" + ) + + if http_error_msg: + raise HTTPError(http_error_msg, response=self) + + def close(self): + """Releases the connection back to the pool. Once this method has been + called the underlying ``raw`` object must not be accessed again. + + *Note: Should not normally need to be called explicitly.* + """ + if not self._content_consumed: + self.raw.close() + + release_conn = getattr(self.raw, "release_conn", None) + if release_conn is not None: + release_conn() diff --git a/wemm/lib/python3.10/site-packages/requests/packages.py b/wemm/lib/python3.10/site-packages/requests/packages.py new file mode 100644 index 0000000000000000000000000000000000000000..5ab3d8e250de8475cb22553f564e5444e02c7460 --- /dev/null +++ b/wemm/lib/python3.10/site-packages/requests/packages.py @@ -0,0 +1,23 @@ +import sys + +from .compat import chardet + +# This code exists for backwards compatibility reasons. +# I don't like it either. Just look the other way. :) + +for package in ("urllib3", "idna"): + locals()[package] = __import__(package) + # This traversal is apparently necessary such that the identities are + # preserved (requests.packages.urllib3.* is urllib3.*) + for mod in list(sys.modules): + if mod == package or mod.startswith(f"{package}."): + sys.modules[f"requests.packages.{mod}"] = sys.modules[mod] + +if chardet is not None: + target = chardet.__name__ + for mod in list(sys.modules): + if mod == target or mod.startswith(f"{target}."): + imported_mod = sys.modules[mod] + sys.modules[f"requests.packages.{mod}"] = imported_mod + mod = mod.replace(target, "chardet") + sys.modules[f"requests.packages.{mod}"] = imported_mod diff --git a/wemm/lib/python3.10/site-packages/requests/sessions.py b/wemm/lib/python3.10/site-packages/requests/sessions.py new file mode 100644 index 0000000000000000000000000000000000000000..b387bc36df7bc064b502adcb3c1a4527dd401fda --- /dev/null +++ b/wemm/lib/python3.10/site-packages/requests/sessions.py @@ -0,0 +1,831 @@ +""" +requests.sessions +~~~~~~~~~~~~~~~~~ + +This module provides a Session object to manage and persist settings across +requests (cookies, auth, proxies). +""" +import os +import sys +import time +from collections import OrderedDict +from datetime import timedelta + +from ._internal_utils import to_native_string +from .adapters import HTTPAdapter +from .auth import _basic_auth_str +from .compat import Mapping, cookielib, urljoin, urlparse +from .cookies import ( + RequestsCookieJar, + cookiejar_from_dict, + extract_cookies_to_jar, + merge_cookies, +) +from .exceptions import ( + ChunkedEncodingError, + ContentDecodingError, + InvalidSchema, + TooManyRedirects, +) +from .hooks import default_hooks, dispatch_hook + +# formerly defined here, reexposed here for backward compatibility +from .models import ( # noqa: F401 + DEFAULT_REDIRECT_LIMIT, + REDIRECT_STATI, + PreparedRequest, + Request, +) +from .status_codes import codes +from .structures import CaseInsensitiveDict +from .utils import ( # noqa: F401 + DEFAULT_PORTS, + default_headers, + get_auth_from_url, + get_environ_proxies, + get_netrc_auth, + requote_uri, + resolve_proxies, + rewind_body, + should_bypass_proxies, + to_key_val_list, +) + +# Preferred clock, based on which one is more accurate on a given system. +if sys.platform == "win32": + preferred_clock = time.perf_counter +else: + preferred_clock = time.time + + +def merge_setting(request_setting, session_setting, dict_class=OrderedDict): + """Determines appropriate setting for a given request, taking into account + the explicit setting on that request, and the setting in the session. If a + setting is a dictionary, they will be merged together using `dict_class` + """ + + if session_setting is None: + return request_setting + + if request_setting is None: + return session_setting + + # Bypass if not a dictionary (e.g. verify) + if not ( + isinstance(session_setting, Mapping) and isinstance(request_setting, Mapping) + ): + return request_setting + + merged_setting = dict_class(to_key_val_list(session_setting)) + merged_setting.update(to_key_val_list(request_setting)) + + # Remove keys that are set to None. Extract keys first to avoid altering + # the dictionary during iteration. + none_keys = [k for (k, v) in merged_setting.items() if v is None] + for key in none_keys: + del merged_setting[key] + + return merged_setting + + +def merge_hooks(request_hooks, session_hooks, dict_class=OrderedDict): + """Properly merges both requests and session hooks. + + This is necessary because when request_hooks == {'response': []}, the + merge breaks Session hooks entirely. + """ + if session_hooks is None or session_hooks.get("response") == []: + return request_hooks + + if request_hooks is None or request_hooks.get("response") == []: + return session_hooks + + return merge_setting(request_hooks, session_hooks, dict_class) + + +class SessionRedirectMixin: + def get_redirect_target(self, resp): + """Receives a Response. Returns a redirect URI or ``None``""" + # Due to the nature of how requests processes redirects this method will + # be called at least once upon the original response and at least twice + # on each subsequent redirect response (if any). + # If a custom mixin is used to handle this logic, it may be advantageous + # to cache the redirect location onto the response object as a private + # attribute. + if resp.is_redirect: + location = resp.headers["location"] + # Currently the underlying http module on py3 decode headers + # in latin1, but empirical evidence suggests that latin1 is very + # rarely used with non-ASCII characters in HTTP headers. + # It is more likely to get UTF8 header rather than latin1. + # This causes incorrect handling of UTF8 encoded location headers. + # To solve this, we re-encode the location in latin1. + location = location.encode("latin1") + return to_native_string(location, "utf8") + return None + + def should_strip_auth(self, old_url, new_url): + """Decide whether Authorization header should be removed when redirecting""" + old_parsed = urlparse(old_url) + new_parsed = urlparse(new_url) + if old_parsed.hostname != new_parsed.hostname: + return True + # Special case: allow http -> https redirect when using the standard + # ports. This isn't specified by RFC 7235, but is kept to avoid + # breaking backwards compatibility with older versions of requests + # that allowed any redirects on the same host. + if ( + old_parsed.scheme == "http" + and old_parsed.port in (80, None) + and new_parsed.scheme == "https" + and new_parsed.port in (443, None) + ): + return False + + # Handle default port usage corresponding to scheme. + changed_port = old_parsed.port != new_parsed.port + changed_scheme = old_parsed.scheme != new_parsed.scheme + default_port = (DEFAULT_PORTS.get(old_parsed.scheme, None), None) + if ( + not changed_scheme + and old_parsed.port in default_port + and new_parsed.port in default_port + ): + return False + + # Standard case: root URI must match + return changed_port or changed_scheme + + def resolve_redirects( + self, + resp, + req, + stream=False, + timeout=None, + verify=True, + cert=None, + proxies=None, + yield_requests=False, + **adapter_kwargs, + ): + """Receives a Response. Returns a generator of Responses or Requests.""" + + hist = [] # keep track of history + + url = self.get_redirect_target(resp) + previous_fragment = urlparse(req.url).fragment + while url: + prepared_request = req.copy() + + # Update history and keep track of redirects. + # resp.history must ignore the original request in this loop + hist.append(resp) + resp.history = hist[1:] + + try: + resp.content # Consume socket so it can be released + except (ChunkedEncodingError, ContentDecodingError, RuntimeError): + resp.raw.read(decode_content=False) + + if len(resp.history) >= self.max_redirects: + raise TooManyRedirects( + f"Exceeded {self.max_redirects} redirects.", response=resp + ) + + # Release the connection back into the pool. + resp.close() + + # Handle redirection without scheme (see: RFC 1808 Section 4) + if url.startswith("//"): + parsed_rurl = urlparse(resp.url) + url = ":".join([to_native_string(parsed_rurl.scheme), url]) + + # Normalize url case and attach previous fragment if needed (RFC 7231 7.1.2) + parsed = urlparse(url) + if parsed.fragment == "" and previous_fragment: + parsed = parsed._replace(fragment=previous_fragment) + elif parsed.fragment: + previous_fragment = parsed.fragment + url = parsed.geturl() + + # Facilitate relative 'location' headers, as allowed by RFC 7231. + # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource') + # Compliant with RFC3986, we percent encode the url. + if not parsed.netloc: + url = urljoin(resp.url, requote_uri(url)) + else: + url = requote_uri(url) + + prepared_request.url = to_native_string(url) + + self.rebuild_method(prepared_request, resp) + + # https://github.com/psf/requests/issues/1084 + if resp.status_code not in ( + codes.temporary_redirect, + codes.permanent_redirect, + ): + # https://github.com/psf/requests/issues/3490 + purged_headers = ("Content-Length", "Content-Type", "Transfer-Encoding") + for header in purged_headers: + prepared_request.headers.pop(header, None) + prepared_request.body = None + + headers = prepared_request.headers + headers.pop("Cookie", None) + + # Extract any cookies sent on the response to the cookiejar + # in the new request. Because we've mutated our copied prepared + # request, use the old one that we haven't yet touched. + extract_cookies_to_jar(prepared_request._cookies, req, resp.raw) + merge_cookies(prepared_request._cookies, self.cookies) + prepared_request.prepare_cookies(prepared_request._cookies) + + # Rebuild auth and proxy information. + proxies = self.rebuild_proxies(prepared_request, proxies) + self.rebuild_auth(prepared_request, resp) + + # A failed tell() sets `_body_position` to `object()`. This non-None + # value ensures `rewindable` will be True, allowing us to raise an + # UnrewindableBodyError, instead of hanging the connection. + rewindable = prepared_request._body_position is not None and ( + "Content-Length" in headers or "Transfer-Encoding" in headers + ) + + # Attempt to rewind consumed file-like object. + if rewindable: + rewind_body(prepared_request) + + # Override the original request. + req = prepared_request + + if yield_requests: + yield req + else: + resp = self.send( + req, + stream=stream, + timeout=timeout, + verify=verify, + cert=cert, + proxies=proxies, + allow_redirects=False, + **adapter_kwargs, + ) + + extract_cookies_to_jar(self.cookies, prepared_request, resp.raw) + + # extract redirect url, if any, for the next loop + url = self.get_redirect_target(resp) + yield resp + + def rebuild_auth(self, prepared_request, response): + """When being redirected we may want to strip authentication from the + request to avoid leaking credentials. This method intelligently removes + and reapplies authentication where possible to avoid credential loss. + """ + headers = prepared_request.headers + url = prepared_request.url + + if "Authorization" in headers and self.should_strip_auth( + response.request.url, url + ): + # If we get redirected to a new host, we should strip out any + # authentication headers. + del headers["Authorization"] + + # .netrc might have more auth for us on our new host. + new_auth = get_netrc_auth(url) if self.trust_env else None + if new_auth is not None: + prepared_request.prepare_auth(new_auth) + + def rebuild_proxies(self, prepared_request, proxies): + """This method re-evaluates the proxy configuration by considering the + environment variables. If we are redirected to a URL covered by + NO_PROXY, we strip the proxy configuration. Otherwise, we set missing + proxy keys for this URL (in case they were stripped by a previous + redirect). + + This method also replaces the Proxy-Authorization header where + necessary. + + :rtype: dict + """ + headers = prepared_request.headers + scheme = urlparse(prepared_request.url).scheme + new_proxies = resolve_proxies(prepared_request, proxies, self.trust_env) + + if "Proxy-Authorization" in headers: + del headers["Proxy-Authorization"] + + try: + username, password = get_auth_from_url(new_proxies[scheme]) + except KeyError: + username, password = None, None + + # urllib3 handles proxy authorization for us in the standard adapter. + # Avoid appending this to TLS tunneled requests where it may be leaked. + if not scheme.startswith("https") and username and password: + headers["Proxy-Authorization"] = _basic_auth_str(username, password) + + return new_proxies + + def rebuild_method(self, prepared_request, response): + """When being redirected we may want to change the method of the request + based on certain specs or browser behavior. + """ + method = prepared_request.method + + # https://tools.ietf.org/html/rfc7231#section-6.4.4 + if response.status_code == codes.see_other and method != "HEAD": + method = "GET" + + # Do what the browsers do, despite standards... + # First, turn 302s into GETs. + if response.status_code == codes.found and method != "HEAD": + method = "GET" + + # Second, if a POST is responded to with a 301, turn it into a GET. + # This bizarre behaviour is explained in Issue 1704. + if response.status_code == codes.moved and method == "POST": + method = "GET" + + prepared_request.method = method + + +class Session(SessionRedirectMixin): + """A Requests session. + + Provides cookie persistence, connection-pooling, and configuration. + + Basic Usage:: + + >>> import requests + >>> s = requests.Session() + >>> s.get('https://httpbin.org/get') + + + Or as a context manager:: + + >>> with requests.Session() as s: + ... s.get('https://httpbin.org/get') + + """ + + __attrs__ = [ + "headers", + "cookies", + "auth", + "proxies", + "hooks", + "params", + "verify", + "cert", + "adapters", + "stream", + "trust_env", + "max_redirects", + ] + + def __init__(self): + #: A case-insensitive dictionary of headers to be sent on each + #: :class:`Request ` sent from this + #: :class:`Session `. + self.headers = default_headers() + + #: Default Authentication tuple or object to attach to + #: :class:`Request `. + self.auth = None + + #: Dictionary mapping protocol or protocol and host to the URL of the proxy + #: (e.g. {'http': 'foo.bar:3128', 'http://host.name': 'foo.bar:4012'}) to + #: be used on each :class:`Request `. + self.proxies = {} + + #: Event-handling hooks. + self.hooks = default_hooks() + + #: Dictionary of querystring data to attach to each + #: :class:`Request `. The dictionary values may be lists for + #: representing multivalued query parameters. + self.params = {} + + #: Stream response content default. + self.stream = False + + #: SSL Verification default. + #: Defaults to `True`, requiring requests to verify the TLS certificate at the + #: remote end. + #: If verify is set to `False`, requests will accept any TLS certificate + #: presented by the server, and will ignore hostname mismatches and/or + #: expired certificates, which will make your application vulnerable to + #: man-in-the-middle (MitM) attacks. + #: Only set this to `False` for testing. + self.verify = True + + #: SSL client certificate default, if String, path to ssl client + #: cert file (.pem). If Tuple, ('cert', 'key') pair. + self.cert = None + + #: Maximum number of redirects allowed. If the request exceeds this + #: limit, a :class:`TooManyRedirects` exception is raised. + #: This defaults to requests.models.DEFAULT_REDIRECT_LIMIT, which is + #: 30. + self.max_redirects = DEFAULT_REDIRECT_LIMIT + + #: Trust environment settings for proxy configuration, default + #: authentication and similar. + self.trust_env = True + + #: A CookieJar containing all currently outstanding cookies set on this + #: session. By default it is a + #: :class:`RequestsCookieJar `, but + #: may be any other ``cookielib.CookieJar`` compatible object. + self.cookies = cookiejar_from_dict({}) + + # Default connection adapters. + self.adapters = OrderedDict() + self.mount("https://", HTTPAdapter()) + self.mount("http://", HTTPAdapter()) + + def __enter__(self): + return self + + def __exit__(self, *args): + self.close() + + def prepare_request(self, request): + """Constructs a :class:`PreparedRequest ` for + transmission and returns it. The :class:`PreparedRequest` has settings + merged from the :class:`Request ` instance and those of the + :class:`Session`. + + :param request: :class:`Request` instance to prepare with this + session's settings. + :rtype: requests.PreparedRequest + """ + cookies = request.cookies or {} + + # Bootstrap CookieJar. + if not isinstance(cookies, cookielib.CookieJar): + cookies = cookiejar_from_dict(cookies) + + # Merge with session cookies + merged_cookies = merge_cookies( + merge_cookies(RequestsCookieJar(), self.cookies), cookies + ) + + # Set environment's basic authentication if not explicitly set. + auth = request.auth + if self.trust_env and not auth and not self.auth: + auth = get_netrc_auth(request.url) + + p = PreparedRequest() + p.prepare( + method=request.method.upper(), + url=request.url, + files=request.files, + data=request.data, + json=request.json, + headers=merge_setting( + request.headers, self.headers, dict_class=CaseInsensitiveDict + ), + params=merge_setting(request.params, self.params), + auth=merge_setting(auth, self.auth), + cookies=merged_cookies, + hooks=merge_hooks(request.hooks, self.hooks), + ) + return p + + def request( + self, + method, + url, + params=None, + data=None, + headers=None, + cookies=None, + files=None, + auth=None, + timeout=None, + allow_redirects=True, + proxies=None, + hooks=None, + stream=None, + verify=None, + cert=None, + json=None, + ): + """Constructs a :class:`Request `, prepares it and sends it. + Returns :class:`Response ` object. + + :param method: method for the new :class:`Request` object. + :param url: URL for the new :class:`Request` object. + :param params: (optional) Dictionary or bytes to be sent in the query + string for the :class:`Request`. + :param data: (optional) Dictionary, list of tuples, bytes, or file-like + object to send in the body of the :class:`Request`. + :param json: (optional) json to send in the body of the + :class:`Request`. + :param headers: (optional) Dictionary of HTTP Headers to send with the + :class:`Request`. + :param cookies: (optional) Dict or CookieJar object to send with the + :class:`Request`. + :param files: (optional) Dictionary of ``'filename': file-like-objects`` + for multipart encoding upload. + :param auth: (optional) Auth tuple or callable to enable + Basic/Digest/Custom HTTP Auth. + :param timeout: (optional) How long to wait for the server to send + data before giving up, as a float, or a :ref:`(connect timeout, + read timeout) ` tuple. + :type timeout: float or tuple + :param allow_redirects: (optional) Set to True by default. + :type allow_redirects: bool + :param proxies: (optional) Dictionary mapping protocol or protocol and + hostname to the URL of the proxy. + :param hooks: (optional) Dictionary mapping hook name to one event or + list of events, event must be callable. + :param stream: (optional) whether to immediately download the response + content. Defaults to ``False``. + :param verify: (optional) Either a boolean, in which case it controls whether we verify + the server's TLS certificate, or a string, in which case it must be a path + to a CA bundle to use. Defaults to ``True``. When set to + ``False``, requests will accept any TLS certificate presented by + the server, and will ignore hostname mismatches and/or expired + certificates, which will make your application vulnerable to + man-in-the-middle (MitM) attacks. Setting verify to ``False`` + may be useful during local development or testing. + :param cert: (optional) if String, path to ssl client cert file (.pem). + If Tuple, ('cert', 'key') pair. + :rtype: requests.Response + """ + # Create the Request. + req = Request( + method=method.upper(), + url=url, + headers=headers, + files=files, + data=data or {}, + json=json, + params=params or {}, + auth=auth, + cookies=cookies, + hooks=hooks, + ) + prep = self.prepare_request(req) + + proxies = proxies or {} + + settings = self.merge_environment_settings( + prep.url, proxies, stream, verify, cert + ) + + # Send the request. + send_kwargs = { + "timeout": timeout, + "allow_redirects": allow_redirects, + } + send_kwargs.update(settings) + resp = self.send(prep, **send_kwargs) + + return resp + + def get(self, url, **kwargs): + r"""Sends a GET request. Returns :class:`Response` object. + + :param url: URL for the new :class:`Request` object. + :param \*\*kwargs: Optional arguments that ``request`` takes. + :rtype: requests.Response + """ + + kwargs.setdefault("allow_redirects", True) + return self.request("GET", url, **kwargs) + + def options(self, url, **kwargs): + r"""Sends a OPTIONS request. Returns :class:`Response` object. + + :param url: URL for the new :class:`Request` object. + :param \*\*kwargs: Optional arguments that ``request`` takes. + :rtype: requests.Response + """ + + kwargs.setdefault("allow_redirects", True) + return self.request("OPTIONS", url, **kwargs) + + def head(self, url, **kwargs): + r"""Sends a HEAD request. Returns :class:`Response` object. + + :param url: URL for the new :class:`Request` object. + :param \*\*kwargs: Optional arguments that ``request`` takes. + :rtype: requests.Response + """ + + kwargs.setdefault("allow_redirects", False) + return self.request("HEAD", url, **kwargs) + + def post(self, url, data=None, json=None, **kwargs): + r"""Sends a POST request. Returns :class:`Response` object. + + :param url: URL for the new :class:`Request` object. + :param data: (optional) Dictionary, list of tuples, bytes, or file-like + object to send in the body of the :class:`Request`. + :param json: (optional) json to send in the body of the :class:`Request`. + :param \*\*kwargs: Optional arguments that ``request`` takes. + :rtype: requests.Response + """ + + return self.request("POST", url, data=data, json=json, **kwargs) + + def put(self, url, data=None, **kwargs): + r"""Sends a PUT request. Returns :class:`Response` object. + + :param url: URL for the new :class:`Request` object. + :param data: (optional) Dictionary, list of tuples, bytes, or file-like + object to send in the body of the :class:`Request`. + :param \*\*kwargs: Optional arguments that ``request`` takes. + :rtype: requests.Response + """ + + return self.request("PUT", url, data=data, **kwargs) + + def patch(self, url, data=None, **kwargs): + r"""Sends a PATCH request. Returns :class:`Response` object. + + :param url: URL for the new :class:`Request` object. + :param data: (optional) Dictionary, list of tuples, bytes, or file-like + object to send in the body of the :class:`Request`. + :param \*\*kwargs: Optional arguments that ``request`` takes. + :rtype: requests.Response + """ + + return self.request("PATCH", url, data=data, **kwargs) + + def delete(self, url, **kwargs): + r"""Sends a DELETE request. Returns :class:`Response` object. + + :param url: URL for the new :class:`Request` object. + :param \*\*kwargs: Optional arguments that ``request`` takes. + :rtype: requests.Response + """ + + return self.request("DELETE", url, **kwargs) + + def send(self, request, **kwargs): + """Send a given PreparedRequest. + + :rtype: requests.Response + """ + # Set defaults that the hooks can utilize to ensure they always have + # the correct parameters to reproduce the previous request. + kwargs.setdefault("stream", self.stream) + kwargs.setdefault("verify", self.verify) + kwargs.setdefault("cert", self.cert) + if "proxies" not in kwargs: + kwargs["proxies"] = resolve_proxies(request, self.proxies, self.trust_env) + + # It's possible that users might accidentally send a Request object. + # Guard against that specific failure case. + if isinstance(request, Request): + raise ValueError("You can only send PreparedRequests.") + + # Set up variables needed for resolve_redirects and dispatching of hooks + allow_redirects = kwargs.pop("allow_redirects", True) + stream = kwargs.get("stream") + hooks = request.hooks + + # Get the appropriate adapter to use + adapter = self.get_adapter(url=request.url) + + # Start time (approximately) of the request + start = preferred_clock() + + # Send the request + r = adapter.send(request, **kwargs) + + # Total elapsed time of the request (approximately) + elapsed = preferred_clock() - start + r.elapsed = timedelta(seconds=elapsed) + + # Response manipulation hooks + r = dispatch_hook("response", hooks, r, **kwargs) + + # Persist cookies + if r.history: + # If the hooks create history then we want those cookies too + for resp in r.history: + extract_cookies_to_jar(self.cookies, resp.request, resp.raw) + + extract_cookies_to_jar(self.cookies, request, r.raw) + + # Resolve redirects if allowed. + if allow_redirects: + # Redirect resolving generator. + gen = self.resolve_redirects(r, request, **kwargs) + history = [resp for resp in gen] + else: + history = [] + + # Shuffle things around if there's history. + if history: + # Insert the first (original) request at the start + history.insert(0, r) + # Get the last request made + r = history.pop() + r.history = history + + # If redirects aren't being followed, store the response on the Request for Response.next(). + if not allow_redirects: + try: + r._next = next( + self.resolve_redirects(r, request, yield_requests=True, **kwargs) + ) + except StopIteration: + pass + + if not stream: + r.content + + return r + + def merge_environment_settings(self, url, proxies, stream, verify, cert): + """ + Check the environment and merge it with some settings. + + :rtype: dict + """ + # Gather clues from the surrounding environment. + if self.trust_env: + # Set environment's proxies. + no_proxy = proxies.get("no_proxy") if proxies is not None else None + env_proxies = get_environ_proxies(url, no_proxy=no_proxy) + for k, v in env_proxies.items(): + proxies.setdefault(k, v) + + # Look for requests environment configuration + # and be compatible with cURL. + if verify is True or verify is None: + verify = ( + os.environ.get("REQUESTS_CA_BUNDLE") + or os.environ.get("CURL_CA_BUNDLE") + or verify + ) + + # Merge all the kwargs. + proxies = merge_setting(proxies, self.proxies) + stream = merge_setting(stream, self.stream) + verify = merge_setting(verify, self.verify) + cert = merge_setting(cert, self.cert) + + return {"proxies": proxies, "stream": stream, "verify": verify, "cert": cert} + + def get_adapter(self, url): + """ + Returns the appropriate connection adapter for the given URL. + + :rtype: requests.adapters.BaseAdapter + """ + for prefix, adapter in self.adapters.items(): + if url.lower().startswith(prefix.lower()): + return adapter + + # Nothing matches :-/ + raise InvalidSchema(f"No connection adapters were found for {url!r}") + + def close(self): + """Closes all adapters and as such the session""" + for v in self.adapters.values(): + v.close() + + def mount(self, prefix, adapter): + """Registers a connection adapter to a prefix. + + Adapters are sorted in descending order by prefix length. + """ + self.adapters[prefix] = adapter + keys_to_move = [k for k in self.adapters if len(k) < len(prefix)] + + for key in keys_to_move: + self.adapters[key] = self.adapters.pop(key) + + def __getstate__(self): + state = {attr: getattr(self, attr, None) for attr in self.__attrs__} + return state + + def __setstate__(self, state): + for attr, value in state.items(): + setattr(self, attr, value) + + +def session(): + """ + Returns a :class:`Session` for context-management. + + .. deprecated:: 1.0.0 + + This method has been deprecated since version 1.0.0 and is only kept for + backwards compatibility. New code should use :class:`~requests.sessions.Session` + to create a session. This may be removed at a future date. + + :rtype: Session + """ + return Session() diff --git a/wemm/lib/python3.10/site-packages/requests/status_codes.py b/wemm/lib/python3.10/site-packages/requests/status_codes.py new file mode 100644 index 0000000000000000000000000000000000000000..c7945a2f06897ed980cc575df2f48d9e6c1a9f7e --- /dev/null +++ b/wemm/lib/python3.10/site-packages/requests/status_codes.py @@ -0,0 +1,128 @@ +r""" +The ``codes`` object defines a mapping from common names for HTTP statuses +to their numerical codes, accessible either as attributes or as dictionary +items. + +Example:: + + >>> import requests + >>> requests.codes['temporary_redirect'] + 307 + >>> requests.codes.teapot + 418 + >>> requests.codes['\o/'] + 200 + +Some codes have multiple names, and both upper- and lower-case versions of +the names are allowed. For example, ``codes.ok``, ``codes.OK``, and +``codes.okay`` all correspond to the HTTP status code 200. +""" + +from .structures import LookupDict + +_codes = { + # Informational. + 100: ("continue",), + 101: ("switching_protocols",), + 102: ("processing", "early-hints"), + 103: ("checkpoint",), + 122: ("uri_too_long", "request_uri_too_long"), + 200: ("ok", "okay", "all_ok", "all_okay", "all_good", "\\o/", "✓"), + 201: ("created",), + 202: ("accepted",), + 203: ("non_authoritative_info", "non_authoritative_information"), + 204: ("no_content",), + 205: ("reset_content", "reset"), + 206: ("partial_content", "partial"), + 207: ("multi_status", "multiple_status", "multi_stati", "multiple_stati"), + 208: ("already_reported",), + 226: ("im_used",), + # Redirection. + 300: ("multiple_choices",), + 301: ("moved_permanently", "moved", "\\o-"), + 302: ("found",), + 303: ("see_other", "other"), + 304: ("not_modified",), + 305: ("use_proxy",), + 306: ("switch_proxy",), + 307: ("temporary_redirect", "temporary_moved", "temporary"), + 308: ( + "permanent_redirect", + "resume_incomplete", + "resume", + ), # "resume" and "resume_incomplete" to be removed in 3.0 + # Client Error. + 400: ("bad_request", "bad"), + 401: ("unauthorized",), + 402: ("payment_required", "payment"), + 403: ("forbidden",), + 404: ("not_found", "-o-"), + 405: ("method_not_allowed", "not_allowed"), + 406: ("not_acceptable",), + 407: ("proxy_authentication_required", "proxy_auth", "proxy_authentication"), + 408: ("request_timeout", "timeout"), + 409: ("conflict",), + 410: ("gone",), + 411: ("length_required",), + 412: ("precondition_failed", "precondition"), + 413: ("request_entity_too_large", "content_too_large"), + 414: ("request_uri_too_large", "uri_too_long"), + 415: ("unsupported_media_type", "unsupported_media", "media_type"), + 416: ( + "requested_range_not_satisfiable", + "requested_range", + "range_not_satisfiable", + ), + 417: ("expectation_failed",), + 418: ("im_a_teapot", "teapot", "i_am_a_teapot"), + 421: ("misdirected_request",), + 422: ("unprocessable_entity", "unprocessable", "unprocessable_content"), + 423: ("locked",), + 424: ("failed_dependency", "dependency"), + 425: ("unordered_collection", "unordered", "too_early"), + 426: ("upgrade_required", "upgrade"), + 428: ("precondition_required", "precondition"), + 429: ("too_many_requests", "too_many"), + 431: ("header_fields_too_large", "fields_too_large"), + 444: ("no_response", "none"), + 449: ("retry_with", "retry"), + 450: ("blocked_by_windows_parental_controls", "parental_controls"), + 451: ("unavailable_for_legal_reasons", "legal_reasons"), + 499: ("client_closed_request",), + # Server Error. + 500: ("internal_server_error", "server_error", "/o\\", "✗"), + 501: ("not_implemented",), + 502: ("bad_gateway",), + 503: ("service_unavailable", "unavailable"), + 504: ("gateway_timeout",), + 505: ("http_version_not_supported", "http_version"), + 506: ("variant_also_negotiates",), + 507: ("insufficient_storage",), + 509: ("bandwidth_limit_exceeded", "bandwidth"), + 510: ("not_extended",), + 511: ("network_authentication_required", "network_auth", "network_authentication"), +} + +codes = LookupDict(name="status_codes") + + +def _init(): + for code, titles in _codes.items(): + for title in titles: + setattr(codes, title, code) + if not title.startswith(("\\", "/")): + setattr(codes, title.upper(), code) + + def doc(code): + names = ", ".join(f"``{n}``" for n in _codes[code]) + return "* %d: %s" % (code, names) + + global __doc__ + __doc__ = ( + __doc__ + "\n" + "\n".join(doc(code) for code in sorted(_codes)) + if __doc__ is not None + else None + ) + + +_init() diff --git a/wemm/lib/python3.10/site-packages/requests/structures.py b/wemm/lib/python3.10/site-packages/requests/structures.py new file mode 100644 index 0000000000000000000000000000000000000000..188e13e4829591facb23ae0e2eda84b9807cb818 --- /dev/null +++ b/wemm/lib/python3.10/site-packages/requests/structures.py @@ -0,0 +1,99 @@ +""" +requests.structures +~~~~~~~~~~~~~~~~~~~ + +Data structures that power Requests. +""" + +from collections import OrderedDict + +from .compat import Mapping, MutableMapping + + +class CaseInsensitiveDict(MutableMapping): + """A case-insensitive ``dict``-like object. + + Implements all methods and operations of + ``MutableMapping`` as well as dict's ``copy``. Also + provides ``lower_items``. + + All keys are expected to be strings. The structure remembers the + case of the last key to be set, and ``iter(instance)``, + ``keys()``, ``items()``, ``iterkeys()``, and ``iteritems()`` + will contain case-sensitive keys. However, querying and contains + testing is case insensitive:: + + cid = CaseInsensitiveDict() + cid['Accept'] = 'application/json' + cid['aCCEPT'] == 'application/json' # True + list(cid) == ['Accept'] # True + + For example, ``headers['content-encoding']`` will return the + value of a ``'Content-Encoding'`` response header, regardless + of how the header name was originally stored. + + If the constructor, ``.update``, or equality comparison + operations are given keys that have equal ``.lower()``s, the + behavior is undefined. + """ + + def __init__(self, data=None, **kwargs): + self._store = OrderedDict() + if data is None: + data = {} + self.update(data, **kwargs) + + def __setitem__(self, key, value): + # Use the lowercased key for lookups, but store the actual + # key alongside the value. + self._store[key.lower()] = (key, value) + + def __getitem__(self, key): + return self._store[key.lower()][1] + + def __delitem__(self, key): + del self._store[key.lower()] + + def __iter__(self): + return (casedkey for casedkey, mappedvalue in self._store.values()) + + def __len__(self): + return len(self._store) + + def lower_items(self): + """Like iteritems(), but with all lowercase keys.""" + return ((lowerkey, keyval[1]) for (lowerkey, keyval) in self._store.items()) + + def __eq__(self, other): + if isinstance(other, Mapping): + other = CaseInsensitiveDict(other) + else: + return NotImplemented + # Compare insensitively + return dict(self.lower_items()) == dict(other.lower_items()) + + # Copy is required + def copy(self): + return CaseInsensitiveDict(self._store.values()) + + def __repr__(self): + return str(dict(self.items())) + + +class LookupDict(dict): + """Dictionary lookup object.""" + + def __init__(self, name=None): + self.name = name + super().__init__() + + def __repr__(self): + return f"" + + def __getitem__(self, key): + # We allow fall-through here, so values default to None + + return self.__dict__.get(key, None) + + def get(self, key, default=None): + return self.__dict__.get(key, default) diff --git a/wemm/lib/python3.10/site-packages/requests/utils.py b/wemm/lib/python3.10/site-packages/requests/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..ae6c42f6cb48d2beaa3b7352bc1d130db3e4e3be --- /dev/null +++ b/wemm/lib/python3.10/site-packages/requests/utils.py @@ -0,0 +1,1096 @@ +""" +requests.utils +~~~~~~~~~~~~~~ + +This module provides utility functions that are used within Requests +that are also useful for external consumption. +""" + +import codecs +import contextlib +import io +import os +import re +import socket +import struct +import sys +import tempfile +import warnings +import zipfile +from collections import OrderedDict + +from urllib3.util import make_headers, parse_url + +from . import certs +from .__version__ import __version__ + +# to_native_string is unused here, but imported here for backwards compatibility +from ._internal_utils import ( # noqa: F401 + _HEADER_VALIDATORS_BYTE, + _HEADER_VALIDATORS_STR, + HEADER_VALIDATORS, + to_native_string, +) +from .compat import ( + Mapping, + basestring, + bytes, + getproxies, + getproxies_environment, + integer_types, +) +from .compat import parse_http_list as _parse_list_header +from .compat import ( + proxy_bypass, + proxy_bypass_environment, + quote, + str, + unquote, + urlparse, + urlunparse, +) +from .cookies import cookiejar_from_dict +from .exceptions import ( + FileModeWarning, + InvalidHeader, + InvalidURL, + UnrewindableBodyError, +) +from .structures import CaseInsensitiveDict + +NETRC_FILES = (".netrc", "_netrc") + +DEFAULT_CA_BUNDLE_PATH = certs.where() + +DEFAULT_PORTS = {"http": 80, "https": 443} + +# Ensure that ', ' is used to preserve previous delimiter behavior. +DEFAULT_ACCEPT_ENCODING = ", ".join( + re.split(r",\s*", make_headers(accept_encoding=True)["accept-encoding"]) +) + + +if sys.platform == "win32": + # provide a proxy_bypass version on Windows without DNS lookups + + def proxy_bypass_registry(host): + try: + import winreg + except ImportError: + return False + + try: + internetSettings = winreg.OpenKey( + winreg.HKEY_CURRENT_USER, + r"Software\Microsoft\Windows\CurrentVersion\Internet Settings", + ) + # ProxyEnable could be REG_SZ or REG_DWORD, normalizing it + proxyEnable = int(winreg.QueryValueEx(internetSettings, "ProxyEnable")[0]) + # ProxyOverride is almost always a string + proxyOverride = winreg.QueryValueEx(internetSettings, "ProxyOverride")[0] + except (OSError, ValueError): + return False + if not proxyEnable or not proxyOverride: + return False + + # make a check value list from the registry entry: replace the + # '' string by the localhost entry and the corresponding + # canonical entry. + proxyOverride = proxyOverride.split(";") + # filter out empty strings to avoid re.match return true in the following code. + proxyOverride = filter(None, proxyOverride) + # now check if we match one of the registry values. + for test in proxyOverride: + if test == "": + if "." not in host: + return True + test = test.replace(".", r"\.") # mask dots + test = test.replace("*", r".*") # change glob sequence + test = test.replace("?", r".") # change glob char + if re.match(test, host, re.I): + return True + return False + + def proxy_bypass(host): # noqa + """Return True, if the host should be bypassed. + + Checks proxy settings gathered from the environment, if specified, + or the registry. + """ + if getproxies_environment(): + return proxy_bypass_environment(host) + else: + return proxy_bypass_registry(host) + + +def dict_to_sequence(d): + """Returns an internal sequence dictionary update.""" + + if hasattr(d, "items"): + d = d.items() + + return d + + +def super_len(o): + total_length = None + current_position = 0 + + if isinstance(o, str): + o = o.encode("utf-8") + + if hasattr(o, "__len__"): + total_length = len(o) + + elif hasattr(o, "len"): + total_length = o.len + + elif hasattr(o, "fileno"): + try: + fileno = o.fileno() + except (io.UnsupportedOperation, AttributeError): + # AttributeError is a surprising exception, seeing as how we've just checked + # that `hasattr(o, 'fileno')`. It happens for objects obtained via + # `Tarfile.extractfile()`, per issue 5229. + pass + else: + total_length = os.fstat(fileno).st_size + + # Having used fstat to determine the file length, we need to + # confirm that this file was opened up in binary mode. + if "b" not in o.mode: + warnings.warn( + ( + "Requests has determined the content-length for this " + "request using the binary size of the file: however, the " + "file has been opened in text mode (i.e. without the 'b' " + "flag in the mode). This may lead to an incorrect " + "content-length. In Requests 3.0, support will be removed " + "for files in text mode." + ), + FileModeWarning, + ) + + if hasattr(o, "tell"): + try: + current_position = o.tell() + except OSError: + # This can happen in some weird situations, such as when the file + # is actually a special file descriptor like stdin. In this + # instance, we don't know what the length is, so set it to zero and + # let requests chunk it instead. + if total_length is not None: + current_position = total_length + else: + if hasattr(o, "seek") and total_length is None: + # StringIO and BytesIO have seek but no usable fileno + try: + # seek to end of file + o.seek(0, 2) + total_length = o.tell() + + # seek back to current position to support + # partially read file-like objects + o.seek(current_position or 0) + except OSError: + total_length = 0 + + if total_length is None: + total_length = 0 + + return max(0, total_length - current_position) + + +def get_netrc_auth(url, raise_errors=False): + """Returns the Requests tuple auth for a given url from netrc.""" + + netrc_file = os.environ.get("NETRC") + if netrc_file is not None: + netrc_locations = (netrc_file,) + else: + netrc_locations = (f"~/{f}" for f in NETRC_FILES) + + try: + from netrc import NetrcParseError, netrc + + netrc_path = None + + for f in netrc_locations: + try: + loc = os.path.expanduser(f) + except KeyError: + # os.path.expanduser can fail when $HOME is undefined and + # getpwuid fails. See https://bugs.python.org/issue20164 & + # https://github.com/psf/requests/issues/1846 + return + + if os.path.exists(loc): + netrc_path = loc + break + + # Abort early if there isn't one. + if netrc_path is None: + return + + ri = urlparse(url) + + # Strip port numbers from netloc. This weird `if...encode`` dance is + # used for Python 3.2, which doesn't support unicode literals. + splitstr = b":" + if isinstance(url, str): + splitstr = splitstr.decode("ascii") + host = ri.netloc.split(splitstr)[0] + + try: + _netrc = netrc(netrc_path).authenticators(host) + if _netrc: + # Return with login / password + login_i = 0 if _netrc[0] else 1 + return (_netrc[login_i], _netrc[2]) + except (NetrcParseError, OSError): + # If there was a parsing error or a permissions issue reading the file, + # we'll just skip netrc auth unless explicitly asked to raise errors. + if raise_errors: + raise + + # App Engine hackiness. + except (ImportError, AttributeError): + pass + + +def guess_filename(obj): + """Tries to guess the filename of the given object.""" + name = getattr(obj, "name", None) + if name and isinstance(name, basestring) and name[0] != "<" and name[-1] != ">": + return os.path.basename(name) + + +def extract_zipped_paths(path): + """Replace nonexistent paths that look like they refer to a member of a zip + archive with the location of an extracted copy of the target, or else + just return the provided path unchanged. + """ + if os.path.exists(path): + # this is already a valid path, no need to do anything further + return path + + # find the first valid part of the provided path and treat that as a zip archive + # assume the rest of the path is the name of a member in the archive + archive, member = os.path.split(path) + while archive and not os.path.exists(archive): + archive, prefix = os.path.split(archive) + if not prefix: + # If we don't check for an empty prefix after the split (in other words, archive remains unchanged after the split), + # we _can_ end up in an infinite loop on a rare corner case affecting a small number of users + break + member = "/".join([prefix, member]) + + if not zipfile.is_zipfile(archive): + return path + + zip_file = zipfile.ZipFile(archive) + if member not in zip_file.namelist(): + return path + + # we have a valid zip archive and a valid member of that archive + tmp = tempfile.gettempdir() + extracted_path = os.path.join(tmp, member.split("/")[-1]) + if not os.path.exists(extracted_path): + # use read + write to avoid the creating nested folders, we only want the file, avoids mkdir racing condition + with atomic_open(extracted_path) as file_handler: + file_handler.write(zip_file.read(member)) + return extracted_path + + +@contextlib.contextmanager +def atomic_open(filename): + """Write a file to the disk in an atomic fashion""" + tmp_descriptor, tmp_name = tempfile.mkstemp(dir=os.path.dirname(filename)) + try: + with os.fdopen(tmp_descriptor, "wb") as tmp_handler: + yield tmp_handler + os.replace(tmp_name, filename) + except BaseException: + os.remove(tmp_name) + raise + + +def from_key_val_list(value): + """Take an object and test to see if it can be represented as a + dictionary. Unless it can not be represented as such, return an + OrderedDict, e.g., + + :: + + >>> from_key_val_list([('key', 'val')]) + OrderedDict([('key', 'val')]) + >>> from_key_val_list('string') + Traceback (most recent call last): + ... + ValueError: cannot encode objects that are not 2-tuples + >>> from_key_val_list({'key': 'val'}) + OrderedDict([('key', 'val')]) + + :rtype: OrderedDict + """ + if value is None: + return None + + if isinstance(value, (str, bytes, bool, int)): + raise ValueError("cannot encode objects that are not 2-tuples") + + return OrderedDict(value) + + +def to_key_val_list(value): + """Take an object and test to see if it can be represented as a + dictionary. If it can be, return a list of tuples, e.g., + + :: + + >>> to_key_val_list([('key', 'val')]) + [('key', 'val')] + >>> to_key_val_list({'key': 'val'}) + [('key', 'val')] + >>> to_key_val_list('string') + Traceback (most recent call last): + ... + ValueError: cannot encode objects that are not 2-tuples + + :rtype: list + """ + if value is None: + return None + + if isinstance(value, (str, bytes, bool, int)): + raise ValueError("cannot encode objects that are not 2-tuples") + + if isinstance(value, Mapping): + value = value.items() + + return list(value) + + +# From mitsuhiko/werkzeug (used with permission). +def parse_list_header(value): + """Parse lists as described by RFC 2068 Section 2. + + In particular, parse comma-separated lists where the elements of + the list may include quoted-strings. A quoted-string could + contain a comma. A non-quoted string could have quotes in the + middle. Quotes are removed automatically after parsing. + + It basically works like :func:`parse_set_header` just that items + may appear multiple times and case sensitivity is preserved. + + The return value is a standard :class:`list`: + + >>> parse_list_header('token, "quoted value"') + ['token', 'quoted value'] + + To create a header from the :class:`list` again, use the + :func:`dump_header` function. + + :param value: a string with a list header. + :return: :class:`list` + :rtype: list + """ + result = [] + for item in _parse_list_header(value): + if item[:1] == item[-1:] == '"': + item = unquote_header_value(item[1:-1]) + result.append(item) + return result + + +# From mitsuhiko/werkzeug (used with permission). +def parse_dict_header(value): + """Parse lists of key, value pairs as described by RFC 2068 Section 2 and + convert them into a python dict: + + >>> d = parse_dict_header('foo="is a fish", bar="as well"') + >>> type(d) is dict + True + >>> sorted(d.items()) + [('bar', 'as well'), ('foo', 'is a fish')] + + If there is no value for a key it will be `None`: + + >>> parse_dict_header('key_without_value') + {'key_without_value': None} + + To create a header from the :class:`dict` again, use the + :func:`dump_header` function. + + :param value: a string with a dict header. + :return: :class:`dict` + :rtype: dict + """ + result = {} + for item in _parse_list_header(value): + if "=" not in item: + result[item] = None + continue + name, value = item.split("=", 1) + if value[:1] == value[-1:] == '"': + value = unquote_header_value(value[1:-1]) + result[name] = value + return result + + +# From mitsuhiko/werkzeug (used with permission). +def unquote_header_value(value, is_filename=False): + r"""Unquotes a header value. (Reversal of :func:`quote_header_value`). + This does not use the real unquoting but what browsers are actually + using for quoting. + + :param value: the header value to unquote. + :rtype: str + """ + if value and value[0] == value[-1] == '"': + # this is not the real unquoting, but fixing this so that the + # RFC is met will result in bugs with internet explorer and + # probably some other browsers as well. IE for example is + # uploading files with "C:\foo\bar.txt" as filename + value = value[1:-1] + + # if this is a filename and the starting characters look like + # a UNC path, then just return the value without quotes. Using the + # replace sequence below on a UNC path has the effect of turning + # the leading double slash into a single slash and then + # _fix_ie_filename() doesn't work correctly. See #458. + if not is_filename or value[:2] != "\\\\": + return value.replace("\\\\", "\\").replace('\\"', '"') + return value + + +def dict_from_cookiejar(cj): + """Returns a key/value dictionary from a CookieJar. + + :param cj: CookieJar object to extract cookies from. + :rtype: dict + """ + + cookie_dict = {cookie.name: cookie.value for cookie in cj} + return cookie_dict + + +def add_dict_to_cookiejar(cj, cookie_dict): + """Returns a CookieJar from a key/value dictionary. + + :param cj: CookieJar to insert cookies into. + :param cookie_dict: Dict of key/values to insert into CookieJar. + :rtype: CookieJar + """ + + return cookiejar_from_dict(cookie_dict, cj) + + +def get_encodings_from_content(content): + """Returns encodings from given content string. + + :param content: bytestring to extract encodings from. + """ + warnings.warn( + ( + "In requests 3.0, get_encodings_from_content will be removed. For " + "more information, please see the discussion on issue #2266. (This" + " warning should only appear once.)" + ), + DeprecationWarning, + ) + + charset_re = re.compile(r']', flags=re.I) + pragma_re = re.compile(r']', flags=re.I) + xml_re = re.compile(r'^<\?xml.*?encoding=["\']*(.+?)["\'>]') + + return ( + charset_re.findall(content) + + pragma_re.findall(content) + + xml_re.findall(content) + ) + + +def _parse_content_type_header(header): + """Returns content type and parameters from given header + + :param header: string + :return: tuple containing content type and dictionary of + parameters + """ + + tokens = header.split(";") + content_type, params = tokens[0].strip(), tokens[1:] + params_dict = {} + items_to_strip = "\"' " + + for param in params: + param = param.strip() + if param: + key, value = param, True + index_of_equals = param.find("=") + if index_of_equals != -1: + key = param[:index_of_equals].strip(items_to_strip) + value = param[index_of_equals + 1 :].strip(items_to_strip) + params_dict[key.lower()] = value + return content_type, params_dict + + +def get_encoding_from_headers(headers): + """Returns encodings from given HTTP Header Dict. + + :param headers: dictionary to extract encoding from. + :rtype: str + """ + + content_type = headers.get("content-type") + + if not content_type: + return None + + content_type, params = _parse_content_type_header(content_type) + + if "charset" in params: + return params["charset"].strip("'\"") + + if "text" in content_type: + return "ISO-8859-1" + + if "application/json" in content_type: + # Assume UTF-8 based on RFC 4627: https://www.ietf.org/rfc/rfc4627.txt since the charset was unset + return "utf-8" + + +def stream_decode_response_unicode(iterator, r): + """Stream decodes an iterator.""" + + if r.encoding is None: + yield from iterator + return + + decoder = codecs.getincrementaldecoder(r.encoding)(errors="replace") + for chunk in iterator: + rv = decoder.decode(chunk) + if rv: + yield rv + rv = decoder.decode(b"", final=True) + if rv: + yield rv + + +def iter_slices(string, slice_length): + """Iterate over slices of a string.""" + pos = 0 + if slice_length is None or slice_length <= 0: + slice_length = len(string) + while pos < len(string): + yield string[pos : pos + slice_length] + pos += slice_length + + +def get_unicode_from_response(r): + """Returns the requested content back in unicode. + + :param r: Response object to get unicode content from. + + Tried: + + 1. charset from content-type + 2. fall back and replace all unicode characters + + :rtype: str + """ + warnings.warn( + ( + "In requests 3.0, get_unicode_from_response will be removed. For " + "more information, please see the discussion on issue #2266. (This" + " warning should only appear once.)" + ), + DeprecationWarning, + ) + + tried_encodings = [] + + # Try charset from content-type + encoding = get_encoding_from_headers(r.headers) + + if encoding: + try: + return str(r.content, encoding) + except UnicodeError: + tried_encodings.append(encoding) + + # Fall back: + try: + return str(r.content, encoding, errors="replace") + except TypeError: + return r.content + + +# The unreserved URI characters (RFC 3986) +UNRESERVED_SET = frozenset( + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" + "0123456789-._~" +) + + +def unquote_unreserved(uri): + """Un-escape any percent-escape sequences in a URI that are unreserved + characters. This leaves all reserved, illegal and non-ASCII bytes encoded. + + :rtype: str + """ + parts = uri.split("%") + for i in range(1, len(parts)): + h = parts[i][0:2] + if len(h) == 2 and h.isalnum(): + try: + c = chr(int(h, 16)) + except ValueError: + raise InvalidURL(f"Invalid percent-escape sequence: '{h}'") + + if c in UNRESERVED_SET: + parts[i] = c + parts[i][2:] + else: + parts[i] = f"%{parts[i]}" + else: + parts[i] = f"%{parts[i]}" + return "".join(parts) + + +def requote_uri(uri): + """Re-quote the given URI. + + This function passes the given URI through an unquote/quote cycle to + ensure that it is fully and consistently quoted. + + :rtype: str + """ + safe_with_percent = "!#$%&'()*+,/:;=?@[]~" + safe_without_percent = "!#$&'()*+,/:;=?@[]~" + try: + # Unquote only the unreserved characters + # Then quote only illegal characters (do not quote reserved, + # unreserved, or '%') + return quote(unquote_unreserved(uri), safe=safe_with_percent) + except InvalidURL: + # We couldn't unquote the given URI, so let's try quoting it, but + # there may be unquoted '%'s in the URI. We need to make sure they're + # properly quoted so they do not cause issues elsewhere. + return quote(uri, safe=safe_without_percent) + + +def address_in_network(ip, net): + """This function allows you to check if an IP belongs to a network subnet + + Example: returns True if ip = 192.168.1.1 and net = 192.168.1.0/24 + returns False if ip = 192.168.1.1 and net = 192.168.100.0/24 + + :rtype: bool + """ + ipaddr = struct.unpack("=L", socket.inet_aton(ip))[0] + netaddr, bits = net.split("/") + netmask = struct.unpack("=L", socket.inet_aton(dotted_netmask(int(bits))))[0] + network = struct.unpack("=L", socket.inet_aton(netaddr))[0] & netmask + return (ipaddr & netmask) == (network & netmask) + + +def dotted_netmask(mask): + """Converts mask from /xx format to xxx.xxx.xxx.xxx + + Example: if mask is 24 function returns 255.255.255.0 + + :rtype: str + """ + bits = 0xFFFFFFFF ^ (1 << 32 - mask) - 1 + return socket.inet_ntoa(struct.pack(">I", bits)) + + +def is_ipv4_address(string_ip): + """ + :rtype: bool + """ + try: + socket.inet_aton(string_ip) + except OSError: + return False + return True + + +def is_valid_cidr(string_network): + """ + Very simple check of the cidr format in no_proxy variable. + + :rtype: bool + """ + if string_network.count("/") == 1: + try: + mask = int(string_network.split("/")[1]) + except ValueError: + return False + + if mask < 1 or mask > 32: + return False + + try: + socket.inet_aton(string_network.split("/")[0]) + except OSError: + return False + else: + return False + return True + + +@contextlib.contextmanager +def set_environ(env_name, value): + """Set the environment variable 'env_name' to 'value' + + Save previous value, yield, and then restore the previous value stored in + the environment variable 'env_name'. + + If 'value' is None, do nothing""" + value_changed = value is not None + if value_changed: + old_value = os.environ.get(env_name) + os.environ[env_name] = value + try: + yield + finally: + if value_changed: + if old_value is None: + del os.environ[env_name] + else: + os.environ[env_name] = old_value + + +def should_bypass_proxies(url, no_proxy): + """ + Returns whether we should bypass proxies or not. + + :rtype: bool + """ + + # Prioritize lowercase environment variables over uppercase + # to keep a consistent behaviour with other http projects (curl, wget). + def get_proxy(key): + return os.environ.get(key) or os.environ.get(key.upper()) + + # First check whether no_proxy is defined. If it is, check that the URL + # we're getting isn't in the no_proxy list. + no_proxy_arg = no_proxy + if no_proxy is None: + no_proxy = get_proxy("no_proxy") + parsed = urlparse(url) + + if parsed.hostname is None: + # URLs don't always have hostnames, e.g. file:/// urls. + return True + + if no_proxy: + # We need to check whether we match here. We need to see if we match + # the end of the hostname, both with and without the port. + no_proxy = (host for host in no_proxy.replace(" ", "").split(",") if host) + + if is_ipv4_address(parsed.hostname): + for proxy_ip in no_proxy: + if is_valid_cidr(proxy_ip): + if address_in_network(parsed.hostname, proxy_ip): + return True + elif parsed.hostname == proxy_ip: + # If no_proxy ip was defined in plain IP notation instead of cidr notation & + # matches the IP of the index + return True + else: + host_with_port = parsed.hostname + if parsed.port: + host_with_port += f":{parsed.port}" + + for host in no_proxy: + if parsed.hostname.endswith(host) or host_with_port.endswith(host): + # The URL does match something in no_proxy, so we don't want + # to apply the proxies on this URL. + return True + + with set_environ("no_proxy", no_proxy_arg): + # parsed.hostname can be `None` in cases such as a file URI. + try: + bypass = proxy_bypass(parsed.hostname) + except (TypeError, socket.gaierror): + bypass = False + + if bypass: + return True + + return False + + +def get_environ_proxies(url, no_proxy=None): + """ + Return a dict of environment proxies. + + :rtype: dict + """ + if should_bypass_proxies(url, no_proxy=no_proxy): + return {} + else: + return getproxies() + + +def select_proxy(url, proxies): + """Select a proxy for the url, if applicable. + + :param url: The url being for the request + :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs + """ + proxies = proxies or {} + urlparts = urlparse(url) + if urlparts.hostname is None: + return proxies.get(urlparts.scheme, proxies.get("all")) + + proxy_keys = [ + urlparts.scheme + "://" + urlparts.hostname, + urlparts.scheme, + "all://" + urlparts.hostname, + "all", + ] + proxy = None + for proxy_key in proxy_keys: + if proxy_key in proxies: + proxy = proxies[proxy_key] + break + + return proxy + + +def resolve_proxies(request, proxies, trust_env=True): + """This method takes proxy information from a request and configuration + input to resolve a mapping of target proxies. This will consider settings + such as NO_PROXY to strip proxy configurations. + + :param request: Request or PreparedRequest + :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs + :param trust_env: Boolean declaring whether to trust environment configs + + :rtype: dict + """ + proxies = proxies if proxies is not None else {} + url = request.url + scheme = urlparse(url).scheme + no_proxy = proxies.get("no_proxy") + new_proxies = proxies.copy() + + if trust_env and not should_bypass_proxies(url, no_proxy=no_proxy): + environ_proxies = get_environ_proxies(url, no_proxy=no_proxy) + + proxy = environ_proxies.get(scheme, environ_proxies.get("all")) + + if proxy: + new_proxies.setdefault(scheme, proxy) + return new_proxies + + +def default_user_agent(name="python-requests"): + """ + Return a string representing the default user agent. + + :rtype: str + """ + return f"{name}/{__version__}" + + +def default_headers(): + """ + :rtype: requests.structures.CaseInsensitiveDict + """ + return CaseInsensitiveDict( + { + "User-Agent": default_user_agent(), + "Accept-Encoding": DEFAULT_ACCEPT_ENCODING, + "Accept": "*/*", + "Connection": "keep-alive", + } + ) + + +def parse_header_links(value): + """Return a list of parsed link headers proxies. + + i.e. Link: ; rel=front; type="image/jpeg",; rel=back;type="image/jpeg" + + :rtype: list + """ + + links = [] + + replace_chars = " '\"" + + value = value.strip(replace_chars) + if not value: + return links + + for val in re.split(", *<", value): + try: + url, params = val.split(";", 1) + except ValueError: + url, params = val, "" + + link = {"url": url.strip("<> '\"")} + + for param in params.split(";"): + try: + key, value = param.split("=") + except ValueError: + break + + link[key.strip(replace_chars)] = value.strip(replace_chars) + + links.append(link) + + return links + + +# Null bytes; no need to recreate these on each call to guess_json_utf +_null = "\x00".encode("ascii") # encoding to ASCII for Python 3 +_null2 = _null * 2 +_null3 = _null * 3 + + +def guess_json_utf(data): + """ + :rtype: str + """ + # JSON always starts with two ASCII characters, so detection is as + # easy as counting the nulls and from their location and count + # determine the encoding. Also detect a BOM, if present. + sample = data[:4] + if sample in (codecs.BOM_UTF32_LE, codecs.BOM_UTF32_BE): + return "utf-32" # BOM included + if sample[:3] == codecs.BOM_UTF8: + return "utf-8-sig" # BOM included, MS style (discouraged) + if sample[:2] in (codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE): + return "utf-16" # BOM included + nullcount = sample.count(_null) + if nullcount == 0: + return "utf-8" + if nullcount == 2: + if sample[::2] == _null2: # 1st and 3rd are null + return "utf-16-be" + if sample[1::2] == _null2: # 2nd and 4th are null + return "utf-16-le" + # Did not detect 2 valid UTF-16 ascii-range characters + if nullcount == 3: + if sample[:3] == _null3: + return "utf-32-be" + if sample[1:] == _null3: + return "utf-32-le" + # Did not detect a valid UTF-32 ascii-range character + return None + + +def prepend_scheme_if_needed(url, new_scheme): + """Given a URL that may or may not have a scheme, prepend the given scheme. + Does not replace a present scheme with the one provided as an argument. + + :rtype: str + """ + parsed = parse_url(url) + scheme, auth, host, port, path, query, fragment = parsed + + # A defect in urlparse determines that there isn't a netloc present in some + # urls. We previously assumed parsing was overly cautious, and swapped the + # netloc and path. Due to a lack of tests on the original defect, this is + # maintained with parse_url for backwards compatibility. + netloc = parsed.netloc + if not netloc: + netloc, path = path, netloc + + if auth: + # parse_url doesn't provide the netloc with auth + # so we'll add it ourselves. + netloc = "@".join([auth, netloc]) + if scheme is None: + scheme = new_scheme + if path is None: + path = "" + + return urlunparse((scheme, netloc, path, "", query, fragment)) + + +def get_auth_from_url(url): + """Given a url with authentication components, extract them into a tuple of + username,password. + + :rtype: (str,str) + """ + parsed = urlparse(url) + + try: + auth = (unquote(parsed.username), unquote(parsed.password)) + except (AttributeError, TypeError): + auth = ("", "") + + return auth + + +def check_header_validity(header): + """Verifies that header parts don't contain leading whitespace + reserved characters, or return characters. + + :param header: tuple, in the format (name, value). + """ + name, value = header + _validate_header_part(header, name, 0) + _validate_header_part(header, value, 1) + + +def _validate_header_part(header, header_part, header_validator_index): + if isinstance(header_part, str): + validator = _HEADER_VALIDATORS_STR[header_validator_index] + elif isinstance(header_part, bytes): + validator = _HEADER_VALIDATORS_BYTE[header_validator_index] + else: + raise InvalidHeader( + f"Header part ({header_part!r}) from {header} " + f"must be of type str or bytes, not {type(header_part)}" + ) + + if not validator.match(header_part): + header_kind = "name" if header_validator_index == 0 else "value" + raise InvalidHeader( + f"Invalid leading whitespace, reserved character(s), or return " + f"character(s) in header {header_kind}: {header_part!r}" + ) + + +def urldefragauth(url): + """ + Given a url remove the fragment and the authentication part. + + :rtype: str + """ + scheme, netloc, path, params, query, fragment = urlparse(url) + + # see func:`prepend_scheme_if_needed` + if not netloc: + netloc, path = path, netloc + + netloc = netloc.rsplit("@", 1)[-1] + + return urlunparse((scheme, netloc, path, params, query, "")) + + +def rewind_body(prepared_request): + """Move file pointer back to its recorded starting position + so it can be read again on redirect. + """ + body_seek = getattr(prepared_request.body, "seek", None) + if body_seek is not None and isinstance( + prepared_request._body_position, integer_types + ): + try: + body_seek(prepared_request._body_position) + except OSError: + raise UnrewindableBodyError( + "An error occurred when rewinding request body for redirect." + ) + else: + raise UnrewindableBodyError("Unable to rewind request body for redirect.") diff --git a/wemm/lib/python3.10/site-packages/safetensors/__init__.py b/wemm/lib/python3.10/site-packages/safetensors/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c9a5d2ca92b5248ce798a19f8e14c3492992cae1 --- /dev/null +++ b/wemm/lib/python3.10/site-packages/safetensors/__init__.py @@ -0,0 +1,9 @@ +# Re-export this +from ._safetensors_rust import ( # noqa: F401 + SafetensorError, + __version__, + deserialize, + safe_open, + serialize, + serialize_file, +) diff --git a/wemm/lib/python3.10/site-packages/safetensors/__init__.pyi b/wemm/lib/python3.10/site-packages/safetensors/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..7781229fe91d0649996e257dccf9f6d0c38823cd --- /dev/null +++ b/wemm/lib/python3.10/site-packages/safetensors/__init__.pyi @@ -0,0 +1,149 @@ +# Generated content DO NOT EDIT +@staticmethod +def deserialize(bytes): + """ + Opens a safetensors lazily and returns tensors as asked + + Args: + data (`bytes`): + The byte content of a file + + Returns: + (`List[str, Dict[str, Dict[str, any]]]`): + The deserialized content is like: + [("tensor_name", {"shape": [2, 3], "dtype": "F32", "data": b"\0\0.." }), (...)] + """ + pass + +@staticmethod +def serialize(tensor_dict, metadata=None): + """ + Serializes raw data. + + Args: + tensor_dict (`Dict[str, Dict[Any]]`): + The tensor dict is like: + {"tensor_name": {"dtype": "F32", "shape": [2, 3], "data": b"\0\0"}} + metadata (`Dict[str, str]`, *optional*): + The optional purely text annotations + + Returns: + (`bytes`): + The serialized content. + """ + pass + +@staticmethod +def serialize_file(tensor_dict, filename, metadata=None): + """ + Serializes raw data. + + Args: + tensor_dict (`Dict[str, Dict[Any]]`): + The tensor dict is like: + {"tensor_name": {"dtype": "F32", "shape": [2, 3], "data": b"\0\0"}} + filename (`str`, or `os.PathLike`): + The name of the file to write into. + metadata (`Dict[str, str]`, *optional*): + The optional purely text annotations + + Returns: + (`bytes`): + The serialized content. + """ + pass + +class safe_open: + """ + Opens a safetensors lazily and returns tensors as asked + + Args: + filename (`str`, or `os.PathLike`): + The filename to open + + framework (`str`): + The framework you want you tensors in. Supported values: + `pt`, `tf`, `flax`, `numpy`. + + device (`str`, defaults to `"cpu"`): + The device on which you want the tensors. + """ + + def __init__(self, filename, framework, device=...): + pass + def __enter__(self): + """ + Start the context manager + """ + pass + def __exit__(self, _exc_type, _exc_value, _traceback): + """ + Exits the context manager + """ + pass + def get_slice(self, name): + """ + Returns a full slice view object + + Args: + name (`str`): + The name of the tensor you want + + Returns: + (`PySafeSlice`): + A dummy object you can slice into to get a real tensor + Example: + ```python + from safetensors import safe_open + + with safe_open("model.safetensors", framework="pt", device=0) as f: + tensor_part = f.get_slice("embedding")[:, ::8] + + ``` + """ + pass + def get_tensor(self, name): + """ + Returns a full tensor + + Args: + name (`str`): + The name of the tensor you want + + Returns: + (`Tensor`): + The tensor in the framework you opened the file for. + + Example: + ```python + from safetensors import safe_open + + with safe_open("model.safetensors", framework="pt", device=0) as f: + tensor = f.get_tensor("embedding") + + ``` + """ + pass + def keys(self): + """ + Returns the names of the tensors in the file. + + Returns: + (`List[str]`): + The name of the tensors contained in that file + """ + pass + def metadata(self): + """ + Return the special non tensor information in the header + + Returns: + (`Dict[str, str]`): + The freeform metadata. + """ + pass + +class SafetensorError(Exception): + """ + Custom Python Exception for Safetensor errors. + """ diff --git a/wemm/lib/python3.10/site-packages/safetensors/__pycache__/__init__.cpython-310.pyc b/wemm/lib/python3.10/site-packages/safetensors/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..efb23e89bd4311060b42c5b54784ba96905fd8e3 Binary files /dev/null and b/wemm/lib/python3.10/site-packages/safetensors/__pycache__/__init__.cpython-310.pyc differ diff --git a/wemm/lib/python3.10/site-packages/safetensors/__pycache__/flax.cpython-310.pyc b/wemm/lib/python3.10/site-packages/safetensors/__pycache__/flax.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3a79a55c84a0d7c8aedcd2cc5333d2a2831bcacd Binary files /dev/null and b/wemm/lib/python3.10/site-packages/safetensors/__pycache__/flax.cpython-310.pyc differ diff --git a/wemm/lib/python3.10/site-packages/safetensors/__pycache__/mlx.cpython-310.pyc b/wemm/lib/python3.10/site-packages/safetensors/__pycache__/mlx.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bfae3fcdae80e0782330a13236367e9c9546addd Binary files /dev/null and b/wemm/lib/python3.10/site-packages/safetensors/__pycache__/mlx.cpython-310.pyc differ diff --git a/wemm/lib/python3.10/site-packages/safetensors/__pycache__/numpy.cpython-310.pyc b/wemm/lib/python3.10/site-packages/safetensors/__pycache__/numpy.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..82244eab6d4c1d5e81c473dc0dcd119c46233ccb Binary files /dev/null and b/wemm/lib/python3.10/site-packages/safetensors/__pycache__/numpy.cpython-310.pyc differ diff --git a/wemm/lib/python3.10/site-packages/safetensors/__pycache__/paddle.cpython-310.pyc b/wemm/lib/python3.10/site-packages/safetensors/__pycache__/paddle.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f52e6363243b17ff92d3a0f39366d58e6f78af28 Binary files /dev/null and b/wemm/lib/python3.10/site-packages/safetensors/__pycache__/paddle.cpython-310.pyc differ diff --git a/wemm/lib/python3.10/site-packages/safetensors/__pycache__/tensorflow.cpython-310.pyc b/wemm/lib/python3.10/site-packages/safetensors/__pycache__/tensorflow.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4877738e444b74f76ef53bdca5529acc66b60167 Binary files /dev/null and b/wemm/lib/python3.10/site-packages/safetensors/__pycache__/tensorflow.cpython-310.pyc differ diff --git a/wemm/lib/python3.10/site-packages/safetensors/__pycache__/torch.cpython-310.pyc b/wemm/lib/python3.10/site-packages/safetensors/__pycache__/torch.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..38bb8047d683a8455bc7bbfadbd05763d72beaee Binary files /dev/null and b/wemm/lib/python3.10/site-packages/safetensors/__pycache__/torch.cpython-310.pyc differ diff --git a/wemm/lib/python3.10/site-packages/safetensors/_safetensors_rust.abi3.so b/wemm/lib/python3.10/site-packages/safetensors/_safetensors_rust.abi3.so new file mode 100644 index 0000000000000000000000000000000000000000..cd8198e3d58ad63ddafdc2593fcc919337330869 --- /dev/null +++ b/wemm/lib/python3.10/site-packages/safetensors/_safetensors_rust.abi3.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d0b3dba08af60863aafd4d9f18abf0b3299ae852f869860655fd869af56bebb7 +size 1089040 diff --git a/wemm/lib/python3.10/site-packages/safetensors/flax.py b/wemm/lib/python3.10/site-packages/safetensors/flax.py new file mode 100644 index 0000000000000000000000000000000000000000..d0b8375e038eff487af33fcfaa4a597aacb5743f --- /dev/null +++ b/wemm/lib/python3.10/site-packages/safetensors/flax.py @@ -0,0 +1,138 @@ +import os +from typing import Dict, Optional, Union + +import numpy as np + +import jax.numpy as jnp +from jax import Array +from safetensors import numpy, safe_open + + +def save(tensors: Dict[str, Array], metadata: Optional[Dict[str, str]] = None) -> bytes: + """ + Saves a dictionary of tensors into raw bytes in safetensors format. + + Args: + tensors (`Dict[str, Array]`): + The incoming tensors. Tensors need to be contiguous and dense. + metadata (`Dict[str, str]`, *optional*, defaults to `None`): + Optional text only metadata you might want to save in your header. + For instance it can be useful to specify more about the underlying + tensors. This is purely informative and does not affect tensor loading. + + Returns: + `bytes`: The raw bytes representing the format + + Example: + + ```python + from safetensors.flax import save + from jax import numpy as jnp + + tensors = {"embedding": jnp.zeros((512, 1024)), "attention": jnp.zeros((256, 256))} + byte_data = save(tensors) + ``` + """ + np_tensors = _jnp2np(tensors) + return numpy.save(np_tensors, metadata=metadata) + + +def save_file( + tensors: Dict[str, Array], + filename: Union[str, os.PathLike], + metadata: Optional[Dict[str, str]] = None, +) -> None: + """ + Saves a dictionary of tensors into raw bytes in safetensors format. + + Args: + tensors (`Dict[str, Array]`): + The incoming tensors. Tensors need to be contiguous and dense. + filename (`str`, or `os.PathLike`)): + The filename we're saving into. + metadata (`Dict[str, str]`, *optional*, defaults to `None`): + Optional text only metadata you might want to save in your header. + For instance it can be useful to specify more about the underlying + tensors. This is purely informative and does not affect tensor loading. + + Returns: + `None` + + Example: + + ```python + from safetensors.flax import save_file + from jax import numpy as jnp + + tensors = {"embedding": jnp.zeros((512, 1024)), "attention": jnp.zeros((256, 256))} + save_file(tensors, "model.safetensors") + ``` + """ + np_tensors = _jnp2np(tensors) + return numpy.save_file(np_tensors, filename, metadata=metadata) + + +def load(data: bytes) -> Dict[str, Array]: + """ + Loads a safetensors file into flax format from pure bytes. + + Args: + data (`bytes`): + The content of a safetensors file + + Returns: + `Dict[str, Array]`: dictionary that contains name as key, value as `Array` on cpu + + Example: + + ```python + from safetensors.flax import load + + file_path = "./my_folder/bert.safetensors" + with open(file_path, "rb") as f: + data = f.read() + + loaded = load(data) + ``` + """ + flat = numpy.load(data) + return _np2jnp(flat) + + +def load_file(filename: Union[str, os.PathLike]) -> Dict[str, Array]: + """ + Loads a safetensors file into flax format. + + Args: + filename (`str`, or `os.PathLike`)): + The name of the file which contains the tensors + + Returns: + `Dict[str, Array]`: dictionary that contains name as key, value as `Array` + + Example: + + ```python + from safetensors.flax import load_file + + file_path = "./my_folder/bert.safetensors" + loaded = load_file(file_path) + ``` + """ + result = {} + with safe_open(filename, framework="flax") as f: + for k in f.keys(): + result[k] = f.get_tensor(k) + return result + + +def _np2jnp(numpy_dict: Dict[str, np.ndarray]) -> Dict[str, Array]: + for k, v in numpy_dict.items(): + numpy_dict[k] = jnp.array(v) + return numpy_dict + + +def _jnp2np(jnp_dict: Dict[str, Array]) -> Dict[str, np.array]: + for k, v in jnp_dict.items(): + jnp_dict[k] = np.asarray(v) + return jnp_dict diff --git a/wemm/lib/python3.10/site-packages/safetensors/mlx.py b/wemm/lib/python3.10/site-packages/safetensors/mlx.py new file mode 100644 index 0000000000000000000000000000000000000000..cf9fe37519c817e4d9db87e8ce53c2dc8b85254f --- /dev/null +++ b/wemm/lib/python3.10/site-packages/safetensors/mlx.py @@ -0,0 +1,138 @@ +import os +from typing import Dict, Optional, Union + +import numpy as np + +import mlx.core as mx +from safetensors import numpy, safe_open + + +def save(tensors: Dict[str, mx.array], metadata: Optional[Dict[str, str]] = None) -> bytes: + """ + Saves a dictionary of tensors into raw bytes in safetensors format. + + Args: + tensors (`Dict[str, mx.array]`): + The incoming tensors. Tensors need to be contiguous and dense. + metadata (`Dict[str, str]`, *optional*, defaults to `None`): + Optional text only metadata you might want to save in your header. + For instance it can be useful to specify more about the underlying + tensors. This is purely informative and does not affect tensor loading. + + Returns: + `bytes`: The raw bytes representing the format + + Example: + + ```python + from safetensors.mlx import save + import mlx.core as mx + + tensors = {"embedding": mx.zeros((512, 1024)), "attention": mx.zeros((256, 256))} + byte_data = save(tensors) + ``` + """ + np_tensors = _mx2np(tensors) + return numpy.save(np_tensors, metadata=metadata) + + +def save_file( + tensors: Dict[str, mx.array], + filename: Union[str, os.PathLike], + metadata: Optional[Dict[str, str]] = None, +) -> None: + """ + Saves a dictionary of tensors into raw bytes in safetensors format. + + Args: + tensors (`Dict[str, mx.array]`): + The incoming tensors. Tensors need to be contiguous and dense. + filename (`str`, or `os.PathLike`)): + The filename we're saving into. + metadata (`Dict[str, str]`, *optional*, defaults to `None`): + Optional text only metadata you might want to save in your header. + For instance it can be useful to specify more about the underlying + tensors. This is purely informative and does not affect tensor loading. + + Returns: + `None` + + Example: + + ```python + from safetensors.mlx import save_file + import mlx.core as mx + + tensors = {"embedding": mx.zeros((512, 1024)), "attention": mx.zeros((256, 256))} + save_file(tensors, "model.safetensors") + ``` + """ + np_tensors = _mx2np(tensors) + return numpy.save_file(np_tensors, filename, metadata=metadata) + + +def load(data: bytes) -> Dict[str, mx.array]: + """ + Loads a safetensors file into MLX format from pure bytes. + + Args: + data (`bytes`): + The content of a safetensors file + + Returns: + `Dict[str, mx.array]`: dictionary that contains name as key, value as `mx.array` + + Example: + + ```python + from safetensors.mlx import load + + file_path = "./my_folder/bert.safetensors" + with open(file_path, "rb") as f: + data = f.read() + + loaded = load(data) + ``` + """ + flat = numpy.load(data) + return _np2mx(flat) + + +def load_file(filename: Union[str, os.PathLike]) -> Dict[str, mx.array]: + """ + Loads a safetensors file into MLX format. + + Args: + filename (`str`, or `os.PathLike`)): + The name of the file which contains the tensors + + Returns: + `Dict[str, mx.array]`: dictionary that contains name as key, value as `mx.array` + + Example: + + ```python + from safetensors.flax import load_file + + file_path = "./my_folder/bert.safetensors" + loaded = load_file(file_path) + ``` + """ + result = {} + with safe_open(filename, framework="mlx") as f: + for k in f.keys(): + result[k] = f.get_tensor(k) + return result + + +def _np2mx(numpy_dict: Dict[str, np.ndarray]) -> Dict[str, mx.array]: + for k, v in numpy_dict.items(): + numpy_dict[k] = mx.array(v) + return numpy_dict + + +def _mx2np(mx_dict: Dict[str, mx.array]) -> Dict[str, np.array]: + new_dict = {} + for k, v in mx_dict.items(): + new_dict[k] = np.asarray(v) + return new_dict diff --git a/wemm/lib/python3.10/site-packages/safetensors/numpy.py b/wemm/lib/python3.10/site-packages/safetensors/numpy.py new file mode 100644 index 0000000000000000000000000000000000000000..0b245f12c1c949456c9b2edb45a11343e6a8099a --- /dev/null +++ b/wemm/lib/python3.10/site-packages/safetensors/numpy.py @@ -0,0 +1,176 @@ +import os +import sys +from typing import Dict, Optional, Union + +import numpy as np + +from safetensors import deserialize, safe_open, serialize, serialize_file + + +def _tobytes(tensor: np.ndarray) -> bytes: + if not _is_little_endian(tensor): + tensor = tensor.byteswap(inplace=False) + return tensor.tobytes() + + +def save(tensor_dict: Dict[str, np.ndarray], metadata: Optional[Dict[str, str]] = None) -> bytes: + """ + Saves a dictionary of tensors into raw bytes in safetensors format. + + Args: + tensor_dict (`Dict[str, np.ndarray]`): + The incoming tensors. Tensors need to be contiguous and dense. + metadata (`Dict[str, str]`, *optional*, defaults to `None`): + Optional text only metadata you might want to save in your header. + For instance it can be useful to specify more about the underlying + tensors. This is purely informative and does not affect tensor loading. + + Returns: + `bytes`: The raw bytes representing the format + + Example: + + ```python + from safetensors.numpy import save + import numpy as np + + tensors = {"embedding": np.zeros((512, 1024)), "attention": np.zeros((256, 256))} + byte_data = save(tensors) + ``` + """ + flattened = {k: {"dtype": v.dtype.name, "shape": v.shape, "data": _tobytes(v)} for k, v in tensor_dict.items()} + serialized = serialize(flattened, metadata=metadata) + result = bytes(serialized) + return result + + +def save_file( + tensor_dict: Dict[str, np.ndarray], filename: Union[str, os.PathLike], metadata: Optional[Dict[str, str]] = None +) -> None: + """ + Saves a dictionary of tensors into raw bytes in safetensors format. + + Args: + tensor_dict (`Dict[str, np.ndarray]`): + The incoming tensors. Tensors need to be contiguous and dense. + filename (`str`, or `os.PathLike`)): + The filename we're saving into. + metadata (`Dict[str, str]`, *optional*, defaults to `None`): + Optional text only metadata you might want to save in your header. + For instance it can be useful to specify more about the underlying + tensors. This is purely informative and does not affect tensor loading. + + Returns: + `None` + + Example: + + ```python + from safetensors.numpy import save_file + import numpy as np + + tensors = {"embedding": np.zeros((512, 1024)), "attention": np.zeros((256, 256))} + save_file(tensors, "model.safetensors") + ``` + """ + flattened = {k: {"dtype": v.dtype.name, "shape": v.shape, "data": _tobytes(v)} for k, v in tensor_dict.items()} + serialize_file(flattened, filename, metadata=metadata) + + +def load(data: bytes) -> Dict[str, np.ndarray]: + """ + Loads a safetensors file into numpy format from pure bytes. + + Args: + data (`bytes`): + The content of a safetensors file + + Returns: + `Dict[str, np.ndarray]`: dictionary that contains name as key, value as `np.ndarray` on cpu + + Example: + + ```python + from safetensors.numpy import load + + file_path = "./my_folder/bert.safetensors" + with open(file_path, "rb") as f: + data = f.read() + + loaded = load(data) + ``` + """ + flat = deserialize(data) + return _view2np(flat) + + +def load_file(filename: Union[str, os.PathLike]) -> Dict[str, np.ndarray]: + """ + Loads a safetensors file into numpy format. + + Args: + filename (`str`, or `os.PathLike`)): + The name of the file which contains the tensors + + Returns: + `Dict[str, np.ndarray]`: dictionary that contains name as key, value as `np.ndarray` + + Example: + + ```python + from safetensors.numpy import load_file + + file_path = "./my_folder/bert.safetensors" + loaded = load_file(file_path) + ``` + """ + result = {} + with safe_open(filename, framework="np") as f: + for k in f.keys(): + result[k] = f.get_tensor(k) + return result + + +_TYPES = { + "F64": np.float64, + "F32": np.float32, + "F16": np.float16, + "I64": np.int64, + "U64": np.uint64, + "I32": np.int32, + "U32": np.uint32, + "I16": np.int16, + "U16": np.uint16, + "I8": np.int8, + "U8": np.uint8, + "BOOL": bool, +} + + +def _getdtype(dtype_str: str) -> np.dtype: + return _TYPES[dtype_str] + + +def _view2np(safeview) -> Dict[str, np.ndarray]: + result = {} + for k, v in safeview: + dtype = _getdtype(v["dtype"]) + arr = np.frombuffer(v["data"], dtype=dtype).reshape(v["shape"]) + result[k] = arr + return result + + +def _is_little_endian(tensor: np.ndarray) -> bool: + byteorder = tensor.dtype.byteorder + if byteorder == "=": + if sys.byteorder == "little": + return True + else: + return False + elif byteorder == "|": + return True + elif byteorder == "<": + return True + elif byteorder == ">": + return False + raise ValueError(f"Unexpected byte order {byteorder}") diff --git a/wemm/lib/python3.10/site-packages/safetensors/paddle.py b/wemm/lib/python3.10/site-packages/safetensors/paddle.py new file mode 100644 index 0000000000000000000000000000000000000000..cec368665de31d17757c0c6621df5dc4926bfab1 --- /dev/null +++ b/wemm/lib/python3.10/site-packages/safetensors/paddle.py @@ -0,0 +1,138 @@ +import os +from typing import Dict, Optional, Union + +import numpy as np + +import paddle +from safetensors import numpy + + +def save(tensors: Dict[str, paddle.Tensor], metadata: Optional[Dict[str, str]] = None) -> bytes: + """ + Saves a dictionary of tensors into raw bytes in safetensors format. + + Args: + tensors (`Dict[str, paddle.Tensor]`): + The incoming tensors. Tensors need to be contiguous and dense. + metadata (`Dict[str, str]`, *optional*, defaults to `None`): + Optional text only metadata you might want to save in your header. + For instance it can be useful to specify more about the underlying + tensors. This is purely informative and does not affect tensor loading. + + Returns: + `bytes`: The raw bytes representing the format + + Example: + + ```python + from safetensors.paddle import save + import paddle + + tensors = {"embedding": paddle.zeros((512, 1024)), "attention": paddle.zeros((256, 256))} + byte_data = save(tensors) + ``` + """ + np_tensors = _paddle2np(tensors) + return numpy.save(np_tensors, metadata=metadata) + + +def save_file( + tensors: Dict[str, paddle.Tensor], + filename: Union[str, os.PathLike], + metadata: Optional[Dict[str, str]] = None, +) -> None: + """ + Saves a dictionary of tensors into raw bytes in safetensors format. + + Args: + tensors (`Dict[str, paddle.Tensor]`): + The incoming tensors. Tensors need to be contiguous and dense. + filename (`str`, or `os.PathLike`)): + The filename we're saving into. + metadata (`Dict[str, str]`, *optional*, defaults to `None`): + Optional text only metadata you might want to save in your header. + For instance it can be useful to specify more about the underlying + tensors. This is purely informative and does not affect tensor loading. + + Returns: + `None` + + Example: + + ```python + from safetensors.paddle import save_file + import paddle + + tensors = {"embedding": paddle.zeros((512, 1024)), "attention": paddle.zeros((256, 256))} + save_file(tensors, "model.safetensors") + ``` + """ + np_tensors = _paddle2np(tensors) + return numpy.save_file(np_tensors, filename, metadata=metadata) + + +def load(data: bytes, device: str = "cpu") -> Dict[str, paddle.Tensor]: + """ + Loads a safetensors file into paddle format from pure bytes. + + Args: + data (`bytes`): + The content of a safetensors file + + Returns: + `Dict[str, paddle.Tensor]`: dictionary that contains name as key, value as `paddle.Tensor` on cpu + + Example: + + ```python + from safetensors.paddle import load + + file_path = "./my_folder/bert.safetensors" + with open(file_path, "rb") as f: + data = f.read() + + loaded = load(data) + ``` + """ + flat = numpy.load(data) + return _np2paddle(flat, device) + + +def load_file(filename: Union[str, os.PathLike], device="cpu") -> Dict[str, paddle.Tensor]: + """ + Loads a safetensors file into paddle format. + + Args: + filename (`str`, or `os.PathLike`)): + The name of the file which contains the tensors + device (`Union[Dict[str, any], str]`, *optional*, defaults to `cpu`): + The device where the tensors need to be located after load. + available options are all regular paddle device locations + + Returns: + `Dict[str, paddle.Tensor]`: dictionary that contains name as key, value as `paddle.Tensor` + + Example: + + ```python + from safetensors.paddle import load_file + + file_path = "./my_folder/bert.safetensors" + loaded = load_file(file_path) + ``` + """ + flat = numpy.load_file(filename) + output = _np2paddle(flat, device) + return output + + +def _np2paddle(numpy_dict: Dict[str, np.ndarray], device: str = "cpu") -> Dict[str, paddle.Tensor]: + for k, v in numpy_dict.items(): + numpy_dict[k] = paddle.to_tensor(v, place=device) + return numpy_dict + + +def _paddle2np(paddle_dict: Dict[str, paddle.Tensor]) -> Dict[str, np.array]: + for k, v in paddle_dict.items(): + paddle_dict[k] = v.detach().cpu().numpy() + return paddle_dict diff --git a/wemm/lib/python3.10/site-packages/safetensors/py.typed b/wemm/lib/python3.10/site-packages/safetensors/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/wemm/lib/python3.10/site-packages/safetensors/tensorflow.py b/wemm/lib/python3.10/site-packages/safetensors/tensorflow.py new file mode 100644 index 0000000000000000000000000000000000000000..e2d74b0522698b3748a7da93753e065f4053beea --- /dev/null +++ b/wemm/lib/python3.10/site-packages/safetensors/tensorflow.py @@ -0,0 +1,137 @@ +import os +from typing import Dict, Optional, Union + +import numpy as np +import tensorflow as tf + +from safetensors import numpy, safe_open + + +def save(tensors: Dict[str, tf.Tensor], metadata: Optional[Dict[str, str]] = None) -> bytes: + """ + Saves a dictionary of tensors into raw bytes in safetensors format. + + Args: + tensors (`Dict[str, tf.Tensor]`): + The incoming tensors. Tensors need to be contiguous and dense. + metadata (`Dict[str, str]`, *optional*, defaults to `None`): + Optional text only metadata you might want to save in your header. + For instance it can be useful to specify more about the underlying + tensors. This is purely informative and does not affect tensor loading. + + Returns: + `bytes`: The raw bytes representing the format + + Example: + + ```python + from safetensors.tensorflow import save + import tensorflow as tf + + tensors = {"embedding": tf.zeros((512, 1024)), "attention": tf.zeros((256, 256))} + byte_data = save(tensors) + ``` + """ + np_tensors = _tf2np(tensors) + return numpy.save(np_tensors, metadata=metadata) + + +def save_file( + tensors: Dict[str, tf.Tensor], + filename: Union[str, os.PathLike], + metadata: Optional[Dict[str, str]] = None, +) -> None: + """ + Saves a dictionary of tensors into raw bytes in safetensors format. + + Args: + tensors (`Dict[str, tf.Tensor]`): + The incoming tensors. Tensors need to be contiguous and dense. + filename (`str`, or `os.PathLike`)): + The filename we're saving into. + metadata (`Dict[str, str]`, *optional*, defaults to `None`): + Optional text only metadata you might want to save in your header. + For instance it can be useful to specify more about the underlying + tensors. This is purely informative and does not affect tensor loading. + + Returns: + `None` + + Example: + + ```python + from safetensors.tensorflow import save_file + import tensorflow as tf + + tensors = {"embedding": tf.zeros((512, 1024)), "attention": tf.zeros((256, 256))} + save_file(tensors, "model.safetensors") + ``` + """ + np_tensors = _tf2np(tensors) + return numpy.save_file(np_tensors, filename, metadata=metadata) + + +def load(data: bytes) -> Dict[str, tf.Tensor]: + """ + Loads a safetensors file into tensorflow format from pure bytes. + + Args: + data (`bytes`): + The content of a safetensors file + + Returns: + `Dict[str, tf.Tensor]`: dictionary that contains name as key, value as `tf.Tensor` on cpu + + Example: + + ```python + from safetensors.tensorflow import load + + file_path = "./my_folder/bert.safetensors" + with open(file_path, "rb") as f: + data = f.read() + + loaded = load(data) + ``` + """ + flat = numpy.load(data) + return _np2tf(flat) + + +def load_file(filename: Union[str, os.PathLike]) -> Dict[str, tf.Tensor]: + """ + Loads a safetensors file into tensorflow format. + + Args: + filename (`str`, or `os.PathLike`)): + The name of the file which contains the tensors + + Returns: + `Dict[str, tf.Tensor]`: dictionary that contains name as key, value as `tf.Tensor` + + Example: + + ```python + from safetensors.tensorflow import load_file + + file_path = "./my_folder/bert.safetensors" + loaded = load_file(file_path) + ``` + """ + result = {} + with safe_open(filename, framework="tf") as f: + for k in f.keys(): + result[k] = f.get_tensor(k) + return result + + +def _np2tf(numpy_dict: Dict[str, np.ndarray]) -> Dict[str, tf.Tensor]: + for k, v in numpy_dict.items(): + numpy_dict[k] = tf.convert_to_tensor(v) + return numpy_dict + + +def _tf2np(tf_dict: Dict[str, tf.Tensor]) -> Dict[str, np.array]: + for k, v in tf_dict.items(): + tf_dict[k] = v.numpy() + return tf_dict diff --git a/wemm/lib/python3.10/site-packages/safetensors/torch.py b/wemm/lib/python3.10/site-packages/safetensors/torch.py new file mode 100644 index 0000000000000000000000000000000000000000..48532ea5996cd807510b97458a0451f092ea0f35 --- /dev/null +++ b/wemm/lib/python3.10/site-packages/safetensors/torch.py @@ -0,0 +1,503 @@ +import os +import sys +from collections import defaultdict +from typing import Any, Dict, List, Optional, Set, Tuple, Union + +import torch + +from safetensors import deserialize, safe_open, serialize, serialize_file + + +def storage_ptr(tensor: torch.Tensor) -> int: + try: + return tensor.untyped_storage().data_ptr() + except Exception: + # Fallback for torch==1.10 + try: + return tensor.storage().data_ptr() + except NotImplementedError: + # Fallback for meta storage + return 0 + + +def _end_ptr(tensor: torch.Tensor) -> int: + if tensor.nelement(): + stop = tensor.view(-1)[-1].data_ptr() + _SIZE[tensor.dtype] + else: + stop = tensor.data_ptr() + return stop + + +def storage_size(tensor: torch.Tensor) -> int: + try: + return tensor.untyped_storage().nbytes() + except AttributeError: + # Fallback for torch==1.10 + try: + return tensor.storage().size() * _SIZE[tensor.dtype] + except NotImplementedError: + # Fallback for meta storage + # On torch >=2.0 this is the tensor size + return tensor.nelement() * _SIZE[tensor.dtype] + + +def _filter_shared_not_shared(tensors: List[Set[str]], state_dict: Dict[str, torch.Tensor]) -> List[Set[str]]: + filtered_tensors = [] + for shared in tensors: + if len(shared) < 2: + filtered_tensors.append(shared) + continue + + areas = [] + for name in shared: + tensor = state_dict[name] + areas.append((tensor.data_ptr(), _end_ptr(tensor), name)) + areas.sort() + + _, last_stop, last_name = areas[0] + filtered_tensors.append({last_name}) + for start, stop, name in areas[1:]: + if start >= last_stop: + filtered_tensors.append({name}) + else: + filtered_tensors[-1].add(name) + last_stop = stop + + return filtered_tensors + + +def _find_shared_tensors(state_dict: Dict[str, torch.Tensor]) -> List[Set[str]]: + tensors = defaultdict(set) + for k, v in state_dict.items(): + if v.device != torch.device("meta") and storage_ptr(v) != 0 and storage_size(v) != 0: + # Need to add device as key because of multiple GPU. + tensors[(v.device, storage_ptr(v), storage_size(v))].add(k) + tensors = list(sorted(tensors.values())) + tensors = _filter_shared_not_shared(tensors, state_dict) + return tensors + + +def _is_complete(tensor: torch.Tensor) -> bool: + return tensor.data_ptr() == storage_ptr(tensor) and tensor.nelement() * _SIZE[tensor.dtype] == storage_size(tensor) + + +def _remove_duplicate_names( + state_dict: Dict[str, torch.Tensor], + *, + preferred_names: Optional[List[str]] = None, + discard_names: Optional[List[str]] = None, +) -> Dict[str, List[str]]: + if preferred_names is None: + preferred_names = [] + preferred_names = set(preferred_names) + if discard_names is None: + discard_names = [] + discard_names = set(discard_names) + + shareds = _find_shared_tensors(state_dict) + to_remove = defaultdict(list) + for shared in shareds: + complete_names = set([name for name in shared if _is_complete(state_dict[name])]) + if not complete_names: + raise RuntimeError( + "Error while trying to find names to remove to save state dict, but found no suitable name to keep" + f" for saving amongst: {shared}. None is covering the entire storage.Refusing to save/load the model" + " since you could be storing much more memory than needed. Please refer to" + " https://huggingface.co/docs/safetensors/torch_shared_tensors for more information. Or open an" + " issue." + ) + + keep_name = sorted(list(complete_names))[0] + + # Mechanism to preferentially select keys to keep + # coming from the on-disk file to allow + # loading models saved with a different choice + # of keep_name + preferred = complete_names.difference(discard_names) + if preferred: + keep_name = sorted(list(preferred))[0] + + if preferred_names: + preferred = preferred_names.intersection(complete_names) + if preferred: + keep_name = sorted(list(preferred))[0] + for name in sorted(shared): + if name != keep_name: + to_remove[keep_name].append(name) + return to_remove + + +def save_model( + model: torch.nn.Module, filename: str, metadata: Optional[Dict[str, str]] = None, force_contiguous: bool = True +): + """ + Saves a given torch model to specified filename. + This method exists specifically to avoid tensor sharing issues which are + not allowed in `safetensors`. [More information on tensor sharing](../torch_shared_tensors) + + Args: + model (`torch.nn.Module`): + The model to save on disk. + filename (`str`): + The filename location to save the file + metadata (`Dict[str, str]`, *optional*): + Extra information to save along with the file. + Some metadata will be added for each dropped tensors. + This information will not be enough to recover the entire + shared structure but might help understanding things + force_contiguous (`boolean`, *optional*, defaults to True): + Forcing the state_dict to be saved as contiguous tensors. + This has no effect on the correctness of the model, but it + could potentially change performance if the layout of the tensor + was chosen specifically for that reason. + """ + state_dict = model.state_dict() + to_removes = _remove_duplicate_names(state_dict) + + for kept_name, to_remove_group in to_removes.items(): + for to_remove in to_remove_group: + if metadata is None: + metadata = {} + + if to_remove not in metadata: + # Do not override user data + metadata[to_remove] = kept_name + del state_dict[to_remove] + if force_contiguous: + state_dict = {k: v.contiguous() for k, v in state_dict.items()} + try: + save_file(state_dict, filename, metadata=metadata) + except ValueError as e: + msg = str(e) + msg += " Or use save_model(..., force_contiguous=True), read the docs for potential caveats." + raise ValueError(msg) + + +def load_model( + model: torch.nn.Module, filename: Union[str, os.PathLike], strict: bool = True, device: Union[str, int] = "cpu" +) -> Tuple[List[str], List[str]]: + """ + Loads a given filename onto a torch model. + This method exists specifically to avoid tensor sharing issues which are + not allowed in `safetensors`. [More information on tensor sharing](../torch_shared_tensors) + + Args: + model (`torch.nn.Module`): + The model to load onto. + filename (`str`, or `os.PathLike`): + The filename location to load the file from. + strict (`bool`, *optional*, defaults to True): + Whether to fail if you're missing keys or having unexpected ones. + When false, the function simply returns missing and unexpected names. + device (`Union[str, int]`, *optional*, defaults to `cpu`): + The device where the tensors need to be located after load. + available options are all regular torch device locations. + + Returns: + `(missing, unexpected): (List[str], List[str])` + `missing` are names in the model which were not modified during loading + `unexpected` are names that are on the file, but weren't used during + the load. + """ + state_dict = load_file(filename, device=device) + model_state_dict = model.state_dict() + to_removes = _remove_duplicate_names(model_state_dict, preferred_names=state_dict.keys()) + missing, unexpected = model.load_state_dict(state_dict, strict=False) + missing = set(missing) + for to_remove_group in to_removes.values(): + for to_remove in to_remove_group: + if to_remove not in missing: + unexpected.append(to_remove) + else: + missing.remove(to_remove) + if strict and (missing or unexpected): + missing_keys = ", ".join([f'"{k}"' for k in sorted(missing)]) + unexpected_keys = ", ".join([f'"{k}"' for k in sorted(unexpected)]) + error = f"Error(s) in loading state_dict for {model.__class__.__name__}:" + if missing: + error += f"\n Missing key(s) in state_dict: {missing_keys}" + if unexpected: + error += f"\n Unexpected key(s) in state_dict: {unexpected_keys}" + raise RuntimeError(error) + return missing, unexpected + + +def save(tensors: Dict[str, torch.Tensor], metadata: Optional[Dict[str, str]] = None) -> bytes: + """ + Saves a dictionary of tensors into raw bytes in safetensors format. + + Args: + tensors (`Dict[str, torch.Tensor]`): + The incoming tensors. Tensors need to be contiguous and dense. + metadata (`Dict[str, str]`, *optional*, defaults to `None`): + Optional text only metadata you might want to save in your header. + For instance it can be useful to specify more about the underlying + tensors. This is purely informative and does not affect tensor loading. + + Returns: + `bytes`: The raw bytes representing the format + + Example: + + ```python + from safetensors.torch import save + import torch + + tensors = {"embedding": torch.zeros((512, 1024)), "attention": torch.zeros((256, 256))} + byte_data = save(tensors) + ``` + """ + serialized = serialize(_flatten(tensors), metadata=metadata) + result = bytes(serialized) + return result + + +def save_file( + tensors: Dict[str, torch.Tensor], + filename: Union[str, os.PathLike], + metadata: Optional[Dict[str, str]] = None, +): + """ + Saves a dictionary of tensors into raw bytes in safetensors format. + + Args: + tensors (`Dict[str, torch.Tensor]`): + The incoming tensors. Tensors need to be contiguous and dense. + filename (`str`, or `os.PathLike`)): + The filename we're saving into. + metadata (`Dict[str, str]`, *optional*, defaults to `None`): + Optional text only metadata you might want to save in your header. + For instance it can be useful to specify more about the underlying + tensors. This is purely informative and does not affect tensor loading. + + Returns: + `None` + + Example: + + ```python + from safetensors.torch import save_file + import torch + + tensors = {"embedding": torch.zeros((512, 1024)), "attention": torch.zeros((256, 256))} + save_file(tensors, "model.safetensors") + ``` + """ + serialize_file(_flatten(tensors), filename, metadata=metadata) + + +def load_file(filename: Union[str, os.PathLike], device: Union[str, int] = "cpu") -> Dict[str, torch.Tensor]: + """ + Loads a safetensors file into torch format. + + Args: + filename (`str`, or `os.PathLike`): + The name of the file which contains the tensors + device (`Union[str, int]`, *optional*, defaults to `cpu`): + The device where the tensors need to be located after load. + available options are all regular torch device locations. + + Returns: + `Dict[str, torch.Tensor]`: dictionary that contains name as key, value as `torch.Tensor` + + Example: + + ```python + from safetensors.torch import load_file + + file_path = "./my_folder/bert.safetensors" + loaded = load_file(file_path) + ``` + """ + result = {} + with safe_open(filename, framework="pt", device=device) as f: + for k in f.keys(): + result[k] = f.get_tensor(k) + return result + + +def load(data: bytes) -> Dict[str, torch.Tensor]: + """ + Loads a safetensors file into torch format from pure bytes. + + Args: + data (`bytes`): + The content of a safetensors file + + Returns: + `Dict[str, torch.Tensor]`: dictionary that contains name as key, value as `torch.Tensor` on cpu + + Example: + + ```python + from safetensors.torch import load + + file_path = "./my_folder/bert.safetensors" + with open(file_path, "rb") as f: + data = f.read() + + loaded = load(data) + ``` + """ + flat = deserialize(data) + return _view2torch(flat) + + +# torch.float8 formats require 2.1; we do not support these dtypes on earlier versions +_float8_e4m3fn = getattr(torch, "float8_e4m3fn", None) +_float8_e5m2 = getattr(torch, "float8_e5m2", None) + +_SIZE = { + torch.int64: 8, + torch.float32: 4, + torch.int32: 4, + torch.bfloat16: 2, + torch.float16: 2, + torch.int16: 2, + torch.uint8: 1, + torch.int8: 1, + torch.bool: 1, + torch.float64: 8, + _float8_e4m3fn: 1, + _float8_e5m2: 1, +} + +_TYPES = { + "F64": torch.float64, + "F32": torch.float32, + "F16": torch.float16, + "BF16": torch.bfloat16, + "I64": torch.int64, + # "U64": torch.uint64, + "I32": torch.int32, + # "U32": torch.uint32, + "I16": torch.int16, + # "U16": torch.uint16, + "I8": torch.int8, + "U8": torch.uint8, + "BOOL": torch.bool, + "F8_E4M3": _float8_e4m3fn, + "F8_E5M2": _float8_e5m2, +} + + +def _getdtype(dtype_str: str) -> torch.dtype: + return _TYPES[dtype_str] + + +def _view2torch(safeview) -> Dict[str, torch.Tensor]: + result = {} + for k, v in safeview: + dtype = _getdtype(v["dtype"]) + if len(v["data"]) == 0: + # Workaround because frombuffer doesn't accept zero-size tensors + assert any(x == 0 for x in v["shape"]) + arr = torch.empty(v["shape"], dtype=dtype) + else: + arr = torch.frombuffer(v["data"], dtype=dtype).reshape(v["shape"]) + if sys.byteorder == "big": + arr = torch.from_numpy(arr.numpy().byteswap(inplace=False)) + result[k] = arr + + return result + + +def _tobytes(tensor: torch.Tensor, name: str) -> bytes: + if tensor.layout != torch.strided: + raise ValueError( + f"You are trying to save a sparse tensor: `{name}` which this library does not support." + " You can make it a dense tensor before saving with `.to_dense()` but be aware this might" + " make a much larger file than needed." + ) + + if not tensor.is_contiguous(): + raise ValueError( + f"You are trying to save a non contiguous tensor: `{name}` which is not allowed. It either means you" + " are trying to save tensors which are reference of each other in which case it's recommended to save" + " only the full tensors, and reslice at load time, or simply call `.contiguous()` on your tensor to" + " pack it before saving." + ) + if tensor.device.type != "cpu": + # Moving tensor to cpu before saving + tensor = tensor.to("cpu") + + import ctypes + + import numpy as np + + # When shape is empty (scalar), np.prod returns a float + # we need a int for the following calculations + length = int(np.prod(tensor.shape).item()) + bytes_per_item = _SIZE[tensor.dtype] + + total_bytes = length * bytes_per_item + + ptr = tensor.data_ptr() + if ptr == 0: + return b"" + newptr = ctypes.cast(ptr, ctypes.POINTER(ctypes.c_ubyte)) + data = np.ctypeslib.as_array(newptr, (total_bytes,)) # no internal copy + if sys.byteorder == "big": + NPDTYPES = { + torch.int64: np.int64, + torch.float32: np.float32, + torch.int32: np.int32, + # XXX: This is ok because both have the same width + torch.bfloat16: np.float16, + torch.float16: np.float16, + torch.int16: np.int16, + torch.uint8: np.uint8, + torch.int8: np.int8, + torch.bool: bool, + torch.float64: np.float64, + # XXX: This is ok because both have the same width and byteswap is a no-op anyway + _float8_e4m3fn: np.uint8, + _float8_e5m2: np.uint8, + } + npdtype = NPDTYPES[tensor.dtype] + # Not in place as that would potentially modify a live running model + data = data.view(npdtype).byteswap(inplace=False) + return data.tobytes() + + +def _flatten(tensors: Dict[str, torch.Tensor]) -> Dict[str, Dict[str, Any]]: + if not isinstance(tensors, dict): + raise ValueError(f"Expected a dict of [str, torch.Tensor] but received {type(tensors)}") + + invalid_tensors = [] + for k, v in tensors.items(): + if not isinstance(v, torch.Tensor): + raise ValueError(f"Key `{k}` is invalid, expected torch.Tensor but received {type(v)}") + + if v.layout != torch.strided: + invalid_tensors.append(k) + if invalid_tensors: + raise ValueError( + f"You are trying to save a sparse tensors: `{invalid_tensors}` which this library does not support." + " You can make it a dense tensor before saving with `.to_dense()` but be aware this might" + " make a much larger file than needed." + ) + + shared_pointers = _find_shared_tensors(tensors) + failing = [] + for names in shared_pointers: + if len(names) > 1: + failing.append(names) + + if failing: + raise RuntimeError( + f""" + Some tensors share memory, this will lead to duplicate memory on disk and potential differences when loading them again: {failing}. + A potential way to correctly save your model is to use `save_model`. + More information at https://huggingface.co/docs/safetensors/torch_shared_tensors + """ + ) + + return { + k: { + "dtype": str(v.dtype).split(".")[-1], + "shape": v.shape, + "data": _tobytes(v, k), + } + for k, v in tensors.items() + } diff --git a/wemm/lib/python3.10/site-packages/transformers/data/__pycache__/__init__.cpython-310.pyc b/wemm/lib/python3.10/site-packages/transformers/data/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f45a4b71649827c85abd7b86b033110a42f1c1d6 Binary files /dev/null and b/wemm/lib/python3.10/site-packages/transformers/data/__pycache__/__init__.cpython-310.pyc differ diff --git a/wemm/lib/python3.10/site-packages/transformers/data/datasets/__init__.py b/wemm/lib/python3.10/site-packages/transformers/data/datasets/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..378894ab4bbb4704b67b1de4ab512f145b889d46 --- /dev/null +++ b/wemm/lib/python3.10/site-packages/transformers/data/datasets/__init__.py @@ -0,0 +1,23 @@ +# Copyright 2020 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from .glue import GlueDataset, GlueDataTrainingArguments +from .language_modeling import ( + LineByLineTextDataset, + LineByLineWithRefDataset, + LineByLineWithSOPTextDataset, + TextDataset, + TextDatasetForNextSentencePrediction, +) +from .squad import SquadDataset, SquadDataTrainingArguments diff --git a/wemm/lib/python3.10/site-packages/transformers/data/datasets/__pycache__/glue.cpython-310.pyc b/wemm/lib/python3.10/site-packages/transformers/data/datasets/__pycache__/glue.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6d52d679f739c767a574ec0b33a2f99c6da0a103 Binary files /dev/null and b/wemm/lib/python3.10/site-packages/transformers/data/datasets/__pycache__/glue.cpython-310.pyc differ diff --git a/wemm/lib/python3.10/site-packages/transformers/data/datasets/glue.py b/wemm/lib/python3.10/site-packages/transformers/data/datasets/glue.py new file mode 100644 index 0000000000000000000000000000000000000000..72df3bece21925d15748d53bd82def67bfdd82bb --- /dev/null +++ b/wemm/lib/python3.10/site-packages/transformers/data/datasets/glue.py @@ -0,0 +1,161 @@ +# Copyright 2020 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import os +import time +import warnings +from dataclasses import dataclass, field +from enum import Enum +from typing import List, Optional, Union + +import torch +from filelock import FileLock +from torch.utils.data import Dataset + +from ...tokenization_utils_base import PreTrainedTokenizerBase +from ...utils import logging +from ..processors.glue import glue_convert_examples_to_features, glue_output_modes, glue_processors +from ..processors.utils import InputFeatures + + +logger = logging.get_logger(__name__) + + +@dataclass +class GlueDataTrainingArguments: + """ + Arguments pertaining to what data we are going to input our model for training and eval. + + Using `HfArgumentParser` we can turn this class into argparse arguments to be able to specify them on the command + line. + """ + + task_name: str = field(metadata={"help": "The name of the task to train on: " + ", ".join(glue_processors.keys())}) + data_dir: str = field( + metadata={"help": "The input data dir. Should contain the .tsv files (or other data files) for the task."} + ) + max_seq_length: int = field( + default=128, + metadata={ + "help": ( + "The maximum total input sequence length after tokenization. Sequences longer " + "than this will be truncated, sequences shorter will be padded." + ) + }, + ) + overwrite_cache: bool = field( + default=False, metadata={"help": "Overwrite the cached training and evaluation sets"} + ) + + def __post_init__(self): + self.task_name = self.task_name.lower() + + +class Split(Enum): + train = "train" + dev = "dev" + test = "test" + + +class GlueDataset(Dataset): + """ + This will be superseded by a framework-agnostic approach soon. + """ + + args: GlueDataTrainingArguments + output_mode: str + features: List[InputFeatures] + + def __init__( + self, + args: GlueDataTrainingArguments, + tokenizer: PreTrainedTokenizerBase, + limit_length: Optional[int] = None, + mode: Union[str, Split] = Split.train, + cache_dir: Optional[str] = None, + ): + warnings.warn( + "This dataset will be removed from the library soon, preprocessing should be handled with the 🤗 Datasets " + "library. You can have a look at this example script for pointers: " + "https://github.com/huggingface/transformers/blob/main/examples/pytorch/text-classification/run_glue.py", + FutureWarning, + ) + self.args = args + self.processor = glue_processors[args.task_name]() + self.output_mode = glue_output_modes[args.task_name] + if isinstance(mode, str): + try: + mode = Split[mode] + except KeyError: + raise KeyError("mode is not a valid split name") + # Load data features from cache or dataset file + cached_features_file = os.path.join( + cache_dir if cache_dir is not None else args.data_dir, + f"cached_{mode.value}_{tokenizer.__class__.__name__}_{args.max_seq_length}_{args.task_name}", + ) + label_list = self.processor.get_labels() + if args.task_name in ["mnli", "mnli-mm"] and tokenizer.__class__.__name__ in ( + "RobertaTokenizer", + "RobertaTokenizerFast", + "XLMRobertaTokenizer", + "BartTokenizer", + "BartTokenizerFast", + ): + # HACK(label indices are swapped in RoBERTa pretrained model) + label_list[1], label_list[2] = label_list[2], label_list[1] + self.label_list = label_list + + # Make sure only the first process in distributed training processes the dataset, + # and the others will use the cache. + lock_path = cached_features_file + ".lock" + with FileLock(lock_path): + if os.path.exists(cached_features_file) and not args.overwrite_cache: + start = time.time() + self.features = torch.load(cached_features_file) + logger.info( + f"Loading features from cached file {cached_features_file} [took %.3f s]", time.time() - start + ) + else: + logger.info(f"Creating features from dataset file at {args.data_dir}") + + if mode == Split.dev: + examples = self.processor.get_dev_examples(args.data_dir) + elif mode == Split.test: + examples = self.processor.get_test_examples(args.data_dir) + else: + examples = self.processor.get_train_examples(args.data_dir) + if limit_length is not None: + examples = examples[:limit_length] + self.features = glue_convert_examples_to_features( + examples, + tokenizer, + max_length=args.max_seq_length, + label_list=label_list, + output_mode=self.output_mode, + ) + start = time.time() + torch.save(self.features, cached_features_file) + # ^ This seems to take a lot of time so I want to investigate why and how we can improve. + logger.info( + f"Saving features into cached file {cached_features_file} [took {time.time() - start:.3f} s]" + ) + + def __len__(self): + return len(self.features) + + def __getitem__(self, i) -> InputFeatures: + return self.features[i] + + def get_labels(self): + return self.label_list diff --git a/wemm/lib/python3.10/site-packages/transformers/data/datasets/language_modeling.py b/wemm/lib/python3.10/site-packages/transformers/data/datasets/language_modeling.py new file mode 100644 index 0000000000000000000000000000000000000000..6c23bf23cf14d4953a278dd3584093d0af084133 --- /dev/null +++ b/wemm/lib/python3.10/site-packages/transformers/data/datasets/language_modeling.py @@ -0,0 +1,530 @@ +# Copyright 2020 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import json +import os +import pickle +import random +import time +import warnings +from typing import Dict, List, Optional + +import torch +from filelock import FileLock +from torch.utils.data import Dataset + +from ...tokenization_utils import PreTrainedTokenizer +from ...utils import logging + + +logger = logging.get_logger(__name__) + + +DEPRECATION_WARNING = ( + "This dataset will be removed from the library soon, preprocessing should be handled with the 🤗 Datasets " + "library. You can have a look at this example script for pointers: {0}" +) + + +class TextDataset(Dataset): + """ + This will be superseded by a framework-agnostic approach soon. + """ + + def __init__( + self, + tokenizer: PreTrainedTokenizer, + file_path: str, + block_size: int, + overwrite_cache=False, + cache_dir: Optional[str] = None, + ): + warnings.warn( + DEPRECATION_WARNING.format( + "https://github.com/huggingface/transformers/blob/main/examples/pytorch/language-modeling/run_mlm.py" + ), + FutureWarning, + ) + if os.path.isfile(file_path) is False: + raise ValueError(f"Input file path {file_path} not found") + + block_size = block_size - tokenizer.num_special_tokens_to_add(pair=False) + + directory, filename = os.path.split(file_path) + cached_features_file = os.path.join( + cache_dir if cache_dir is not None else directory, + f"cached_lm_{tokenizer.__class__.__name__}_{block_size}_{filename}", + ) + + # Make sure only the first process in distributed training processes the dataset, + # and the others will use the cache. + lock_path = cached_features_file + ".lock" + with FileLock(lock_path): + if os.path.exists(cached_features_file) and not overwrite_cache: + start = time.time() + with open(cached_features_file, "rb") as handle: + self.examples = pickle.load(handle) + logger.info( + f"Loading features from cached file {cached_features_file} [took %.3f s]", time.time() - start + ) + + else: + logger.info(f"Creating features from dataset file at {directory}") + + self.examples = [] + with open(file_path, encoding="utf-8") as f: + text = f.read() + + tokenized_text = tokenizer.convert_tokens_to_ids(tokenizer.tokenize(text)) + + for i in range(0, len(tokenized_text) - block_size + 1, block_size): # Truncate in block of block_size + self.examples.append( + tokenizer.build_inputs_with_special_tokens(tokenized_text[i : i + block_size]) + ) + # Note that we are losing the last truncated example here for the sake of simplicity (no padding) + # If your dataset is small, first you should look for a bigger one :-) and second you + # can change this behavior by adding (model specific) padding. + + start = time.time() + with open(cached_features_file, "wb") as handle: + pickle.dump(self.examples, handle, protocol=pickle.HIGHEST_PROTOCOL) + logger.info( + f"Saving features into cached file {cached_features_file} [took {time.time() - start:.3f} s]" + ) + + def __len__(self): + return len(self.examples) + + def __getitem__(self, i) -> torch.Tensor: + return torch.tensor(self.examples[i], dtype=torch.long) + + +class LineByLineTextDataset(Dataset): + """ + This will be superseded by a framework-agnostic approach soon. + """ + + def __init__(self, tokenizer: PreTrainedTokenizer, file_path: str, block_size: int): + warnings.warn( + DEPRECATION_WARNING.format( + "https://github.com/huggingface/transformers/blob/main/examples/pytorch/language-modeling/run_mlm.py" + ), + FutureWarning, + ) + if os.path.isfile(file_path) is False: + raise ValueError(f"Input file path {file_path} not found") + # Here, we do not cache the features, operating under the assumption + # that we will soon use fast multithreaded tokenizers from the + # `tokenizers` repo everywhere =) + logger.info(f"Creating features from dataset file at {file_path}") + + with open(file_path, encoding="utf-8") as f: + lines = [line for line in f.read().splitlines() if (len(line) > 0 and not line.isspace())] + + batch_encoding = tokenizer(lines, add_special_tokens=True, truncation=True, max_length=block_size) + self.examples = batch_encoding["input_ids"] + self.examples = [{"input_ids": torch.tensor(e, dtype=torch.long)} for e in self.examples] + + def __len__(self): + return len(self.examples) + + def __getitem__(self, i) -> Dict[str, torch.tensor]: + return self.examples[i] + + +class LineByLineWithRefDataset(Dataset): + """ + This will be superseded by a framework-agnostic approach soon. + """ + + def __init__(self, tokenizer: PreTrainedTokenizer, file_path: str, block_size: int, ref_path: str): + warnings.warn( + DEPRECATION_WARNING.format( + "https://github.com/huggingface/transformers/blob/main/examples/pytorch/language-modeling/run_mlm_wwm.py" + ), + FutureWarning, + ) + if os.path.isfile(file_path) is False: + raise ValueError(f"Input file path {file_path} not found") + if os.path.isfile(ref_path) is False: + raise ValueError(f"Ref file path {file_path} not found") + # Here, we do not cache the features, operating under the assumption + # that we will soon use fast multithreaded tokenizers from the + # `tokenizers` repo everywhere =) + logger.info(f"Creating features from dataset file at {file_path}") + logger.info(f"Use ref segment results at {ref_path}") + with open(file_path, encoding="utf-8") as f: + data = f.readlines() # use this method to avoid delimiter '\u2029' to split a line + data = [line.strip() for line in data if len(line) > 0 and not line.isspace()] + # Get ref inf from file + with open(ref_path, encoding="utf-8") as f: + ref = [json.loads(line) for line in f.read().splitlines() if (len(line) > 0 and not line.isspace())] + if len(data) != len(ref): + raise ValueError( + f"Length of Input file should be equal to Ref file. But the length of {file_path} is {len(data)} " + f"while length of {ref_path} is {len(ref)}" + ) + + batch_encoding = tokenizer(data, add_special_tokens=True, truncation=True, max_length=block_size) + self.examples = batch_encoding["input_ids"] + self.examples = [{"input_ids": torch.tensor(e, dtype=torch.long)} for e in self.examples] + + n = len(self.examples) + for i in range(n): + self.examples[i]["chinese_ref"] = torch.tensor(ref[i], dtype=torch.long) + + def __len__(self): + return len(self.examples) + + def __getitem__(self, i) -> Dict[str, torch.tensor]: + return self.examples[i] + + +class LineByLineWithSOPTextDataset(Dataset): + """ + Dataset for sentence order prediction task, prepare sentence pairs for SOP task + """ + + def __init__(self, tokenizer: PreTrainedTokenizer, file_dir: str, block_size: int): + warnings.warn( + DEPRECATION_WARNING.format( + "https://github.com/huggingface/transformers/blob/main/examples/pytorch/language-modeling/run_mlm.py" + ), + FutureWarning, + ) + if os.path.isdir(file_dir) is False: + raise ValueError(f"{file_dir} is not a directory") + logger.info(f"Creating features from dataset file folder at {file_dir}") + self.examples = [] + # TODO: randomness could apply a random seed, ex. rng = random.Random(random_seed) + # file path looks like ./dataset/wiki_1, ./dataset/wiki_2 + for file_name in os.listdir(file_dir): + file_path = os.path.join(file_dir, file_name) + if os.path.isfile(file_path) is False: + raise ValueError(f"{file_path} is not a file") + article_open = False + with open(file_path, encoding="utf-8") as f: + original_lines = f.readlines() + article_lines = [] + for line in original_lines: + if "" in line: + article_open = False + document = [ + tokenizer.convert_tokens_to_ids(tokenizer.tokenize(line)) + for line in article_lines[1:] + if (len(line) > 0 and not line.isspace()) + ] + + examples = self.create_examples_from_document(document, block_size, tokenizer) + self.examples.extend(examples) + article_lines = [] + else: + if article_open: + article_lines.append(line) + + logger.info("Dataset parse finished.") + + def create_examples_from_document(self, document, block_size, tokenizer, short_seq_prob=0.1): + """Creates examples for a single document.""" + + # Account for special tokens + max_num_tokens = block_size - tokenizer.num_special_tokens_to_add(pair=True) + + # We *usually* want to fill up the entire sequence since we are padding + # to `block_size` anyways, so short sequences are generally wasted + # computation. However, we *sometimes* + # (i.e., short_seq_prob == 0.1 == 10% of the time) want to use shorter + # sequences to minimize the mismatch between pretraining and fine-tuning. + # The `target_seq_length` is just a rough target however, whereas + # `block_size` is a hard limit. + target_seq_length = max_num_tokens + if random.random() < short_seq_prob: + target_seq_length = random.randint(2, max_num_tokens) + + # We DON'T just concatenate all of the tokens from a document into a long + # sequence and choose an arbitrary split point because this would make the + # next sentence prediction task too easy. Instead, we split the input into + # segments "A" and "B" based on the actual "sentences" provided by the user + # input. + examples = [] + current_chunk = [] # a buffer stored current working segments + current_length = 0 + i = 0 + while i < len(document): + segment = document[i] # get a segment + if not segment: + i += 1 + continue + current_chunk.append(segment) # add a segment to current chunk + current_length += len(segment) # overall token length + # if current length goes to the target length or reaches the end of file, start building token a and b + if i == len(document) - 1 or current_length >= target_seq_length: + if current_chunk: + # `a_end` is how many segments from `current_chunk` go into the `A` (first) sentence. + a_end = 1 + # if current chunk has more than 2 sentences, pick part of it `A` (first) sentence + if len(current_chunk) >= 2: + a_end = random.randint(1, len(current_chunk) - 1) + # token a + tokens_a = [] + for j in range(a_end): + tokens_a.extend(current_chunk[j]) + + # token b + tokens_b = [] + for j in range(a_end, len(current_chunk)): + tokens_b.extend(current_chunk[j]) + + if len(tokens_a) == 0 or len(tokens_b) == 0: + continue + + # switch tokens_a and tokens_b randomly + if random.random() < 0.5: + is_next = False + tokens_a, tokens_b = tokens_b, tokens_a + else: + is_next = True + + def truncate_seq_pair(tokens_a, tokens_b, max_num_tokens): + """Truncates a pair of sequences to a maximum sequence length.""" + while True: + total_length = len(tokens_a) + len(tokens_b) + if total_length <= max_num_tokens: + break + trunc_tokens = tokens_a if len(tokens_a) > len(tokens_b) else tokens_b + if not (len(trunc_tokens) >= 1): + raise ValueError("Sequence length to be truncated must be no less than one") + # We want to sometimes truncate from the front and sometimes from the + # back to add more randomness and avoid biases. + if random.random() < 0.5: + del trunc_tokens[0] + else: + trunc_tokens.pop() + + truncate_seq_pair(tokens_a, tokens_b, max_num_tokens) + if not (len(tokens_a) >= 1): + raise ValueError(f"Length of sequence a is {len(tokens_a)} which must be no less than 1") + if not (len(tokens_b) >= 1): + raise ValueError(f"Length of sequence b is {len(tokens_b)} which must be no less than 1") + + # add special tokens + input_ids = tokenizer.build_inputs_with_special_tokens(tokens_a, tokens_b) + # add token type ids, 0 for sentence a, 1 for sentence b + token_type_ids = tokenizer.create_token_type_ids_from_sequences(tokens_a, tokens_b) + + example = { + "input_ids": torch.tensor(input_ids, dtype=torch.long), + "token_type_ids": torch.tensor(token_type_ids, dtype=torch.long), + "sentence_order_label": torch.tensor(0 if is_next else 1, dtype=torch.long), + } + examples.append(example) + current_chunk = [] # clear current chunk + current_length = 0 # reset current text length + i += 1 # go to next line + return examples + + def __len__(self): + return len(self.examples) + + def __getitem__(self, i) -> Dict[str, torch.tensor]: + return self.examples[i] + + +class TextDatasetForNextSentencePrediction(Dataset): + """ + This will be superseded by a framework-agnostic approach soon. + """ + + def __init__( + self, + tokenizer: PreTrainedTokenizer, + file_path: str, + block_size: int, + overwrite_cache=False, + short_seq_probability=0.1, + nsp_probability=0.5, + ): + warnings.warn( + DEPRECATION_WARNING.format( + "https://github.com/huggingface/transformers/blob/main/examples/pytorch/language-modeling/run_mlm.py" + ), + FutureWarning, + ) + if not os.path.isfile(file_path): + raise ValueError(f"Input file path {file_path} not found") + + self.short_seq_probability = short_seq_probability + self.nsp_probability = nsp_probability + + directory, filename = os.path.split(file_path) + cached_features_file = os.path.join( + directory, + f"cached_nsp_{tokenizer.__class__.__name__}_{block_size}_{filename}", + ) + + self.tokenizer = tokenizer + + # Make sure only the first process in distributed training processes the dataset, + # and the others will use the cache. + lock_path = cached_features_file + ".lock" + + # Input file format: + # (1) One sentence per line. These should ideally be actual sentences, not + # entire paragraphs or arbitrary spans of text. (Because we use the + # sentence boundaries for the "next sentence prediction" task). + # (2) Blank lines between documents. Document boundaries are needed so + # that the "next sentence prediction" task doesn't span between documents. + # + # Example: + # I am very happy. + # Here is the second sentence. + # + # A new document. + + with FileLock(lock_path): + if os.path.exists(cached_features_file) and not overwrite_cache: + start = time.time() + with open(cached_features_file, "rb") as handle: + self.examples = pickle.load(handle) + logger.info( + f"Loading features from cached file {cached_features_file} [took %.3f s]", time.time() - start + ) + else: + logger.info(f"Creating features from dataset file at {directory}") + + self.documents = [[]] + with open(file_path, encoding="utf-8") as f: + while True: + line = f.readline() + if not line: + break + line = line.strip() + + # Empty lines are used as document delimiters + if not line and len(self.documents[-1]) != 0: + self.documents.append([]) + tokens = tokenizer.tokenize(line) + tokens = tokenizer.convert_tokens_to_ids(tokens) + if tokens: + self.documents[-1].append(tokens) + + logger.info(f"Creating examples from {len(self.documents)} documents.") + self.examples = [] + for doc_index, document in enumerate(self.documents): + self.create_examples_from_document(document, doc_index, block_size) + + start = time.time() + with open(cached_features_file, "wb") as handle: + pickle.dump(self.examples, handle, protocol=pickle.HIGHEST_PROTOCOL) + logger.info( + f"Saving features into cached file {cached_features_file} [took {time.time() - start:.3f} s]" + ) + + def create_examples_from_document(self, document: List[List[int]], doc_index: int, block_size: int): + """Creates examples for a single document.""" + + max_num_tokens = block_size - self.tokenizer.num_special_tokens_to_add(pair=True) + + # We *usually* want to fill up the entire sequence since we are padding + # to `block_size` anyways, so short sequences are generally wasted + # computation. However, we *sometimes* + # (i.e., short_seq_prob == 0.1 == 10% of the time) want to use shorter + # sequences to minimize the mismatch between pretraining and fine-tuning. + # The `target_seq_length` is just a rough target however, whereas + # `block_size` is a hard limit. + target_seq_length = max_num_tokens + if random.random() < self.short_seq_probability: + target_seq_length = random.randint(2, max_num_tokens) + + current_chunk = [] # a buffer stored current working segments + current_length = 0 + i = 0 + + while i < len(document): + segment = document[i] + current_chunk.append(segment) + current_length += len(segment) + if i == len(document) - 1 or current_length >= target_seq_length: + if current_chunk: + # `a_end` is how many segments from `current_chunk` go into the `A` + # (first) sentence. + a_end = 1 + if len(current_chunk) >= 2: + a_end = random.randint(1, len(current_chunk) - 1) + + tokens_a = [] + for j in range(a_end): + tokens_a.extend(current_chunk[j]) + + tokens_b = [] + + if len(current_chunk) == 1 or random.random() < self.nsp_probability: + is_random_next = True + target_b_length = target_seq_length - len(tokens_a) + + # This should rarely go for more than one iteration for large + # corpora. However, just to be careful, we try to make sure that + # the random document is not the same as the document + # we're processing. + for _ in range(10): + random_document_index = random.randint(0, len(self.documents) - 1) + if random_document_index != doc_index: + break + + random_document = self.documents[random_document_index] + random_start = random.randint(0, len(random_document) - 1) + for j in range(random_start, len(random_document)): + tokens_b.extend(random_document[j]) + if len(tokens_b) >= target_b_length: + break + # We didn't actually use these segments so we "put them back" so + # they don't go to waste. + num_unused_segments = len(current_chunk) - a_end + i -= num_unused_segments + # Actual next + else: + is_random_next = False + for j in range(a_end, len(current_chunk)): + tokens_b.extend(current_chunk[j]) + + if not (len(tokens_a) >= 1): + raise ValueError(f"Length of sequence a is {len(tokens_a)} which must be no less than 1") + if not (len(tokens_b) >= 1): + raise ValueError(f"Length of sequence b is {len(tokens_b)} which must be no less than 1") + + # add special tokens + input_ids = self.tokenizer.build_inputs_with_special_tokens(tokens_a, tokens_b) + # add token type ids, 0 for sentence a, 1 for sentence b + token_type_ids = self.tokenizer.create_token_type_ids_from_sequences(tokens_a, tokens_b) + + example = { + "input_ids": torch.tensor(input_ids, dtype=torch.long), + "token_type_ids": torch.tensor(token_type_ids, dtype=torch.long), + "next_sentence_label": torch.tensor(1 if is_random_next else 0, dtype=torch.long), + } + + self.examples.append(example) + + current_chunk = [] + current_length = 0 + + i += 1 + + def __len__(self): + return len(self.examples) + + def __getitem__(self, i): + return self.examples[i] diff --git a/wemm/lib/python3.10/site-packages/transformers/data/datasets/squad.py b/wemm/lib/python3.10/site-packages/transformers/data/datasets/squad.py new file mode 100644 index 0000000000000000000000000000000000000000..d81217d818afff5e297e6992d979847cf7c0f4cc --- /dev/null +++ b/wemm/lib/python3.10/site-packages/transformers/data/datasets/squad.py @@ -0,0 +1,229 @@ +# Copyright 2020 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import os +import time +from dataclasses import dataclass, field +from enum import Enum +from typing import Dict, List, Optional, Union + +import torch +from filelock import FileLock +from torch.utils.data import Dataset + +from ...models.auto.modeling_auto import MODEL_FOR_QUESTION_ANSWERING_MAPPING +from ...tokenization_utils import PreTrainedTokenizer +from ...utils import logging +from ..processors.squad import SquadFeatures, SquadV1Processor, SquadV2Processor, squad_convert_examples_to_features + + +logger = logging.get_logger(__name__) + +MODEL_CONFIG_CLASSES = list(MODEL_FOR_QUESTION_ANSWERING_MAPPING.keys()) +MODEL_TYPES = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES) + + +@dataclass +class SquadDataTrainingArguments: + """ + Arguments pertaining to what data we are going to input our model for training and eval. + """ + + model_type: str = field( + default=None, metadata={"help": "Model type selected in the list: " + ", ".join(MODEL_TYPES)} + ) + data_dir: str = field( + default=None, metadata={"help": "The input data dir. Should contain the .json files for the SQuAD task."} + ) + max_seq_length: int = field( + default=128, + metadata={ + "help": ( + "The maximum total input sequence length after tokenization. Sequences longer " + "than this will be truncated, sequences shorter will be padded." + ) + }, + ) + doc_stride: int = field( + default=128, + metadata={"help": "When splitting up a long document into chunks, how much stride to take between chunks."}, + ) + max_query_length: int = field( + default=64, + metadata={ + "help": ( + "The maximum number of tokens for the question. Questions longer than this will " + "be truncated to this length." + ) + }, + ) + max_answer_length: int = field( + default=30, + metadata={ + "help": ( + "The maximum length of an answer that can be generated. This is needed because the start " + "and end predictions are not conditioned on one another." + ) + }, + ) + overwrite_cache: bool = field( + default=False, metadata={"help": "Overwrite the cached training and evaluation sets"} + ) + version_2_with_negative: bool = field( + default=False, metadata={"help": "If true, the SQuAD examples contain some that do not have an answer."} + ) + null_score_diff_threshold: float = field( + default=0.0, metadata={"help": "If null_score - best_non_null is greater than the threshold predict null."} + ) + n_best_size: int = field( + default=20, metadata={"help": "If null_score - best_non_null is greater than the threshold predict null."} + ) + lang_id: int = field( + default=0, + metadata={ + "help": ( + "language id of input for language-specific xlm models (see" + " tokenization_xlm.PRETRAINED_INIT_CONFIGURATION)" + ) + }, + ) + threads: int = field(default=1, metadata={"help": "multiple threads for converting example to features"}) + + +class Split(Enum): + train = "train" + dev = "dev" + + +class SquadDataset(Dataset): + """ + This will be superseded by a framework-agnostic approach soon. + """ + + args: SquadDataTrainingArguments + features: List[SquadFeatures] + mode: Split + is_language_sensitive: bool + + def __init__( + self, + args: SquadDataTrainingArguments, + tokenizer: PreTrainedTokenizer, + limit_length: Optional[int] = None, + mode: Union[str, Split] = Split.train, + is_language_sensitive: Optional[bool] = False, + cache_dir: Optional[str] = None, + dataset_format: Optional[str] = "pt", + ): + self.args = args + self.is_language_sensitive = is_language_sensitive + self.processor = SquadV2Processor() if args.version_2_with_negative else SquadV1Processor() + if isinstance(mode, str): + try: + mode = Split[mode] + except KeyError: + raise KeyError("mode is not a valid split name") + self.mode = mode + # Load data features from cache or dataset file + version_tag = "v2" if args.version_2_with_negative else "v1" + cached_features_file = os.path.join( + cache_dir if cache_dir is not None else args.data_dir, + f"cached_{mode.value}_{tokenizer.__class__.__name__}_{args.max_seq_length}_{version_tag}", + ) + + # Make sure only the first process in distributed training processes the dataset, + # and the others will use the cache. + lock_path = cached_features_file + ".lock" + with FileLock(lock_path): + if os.path.exists(cached_features_file) and not args.overwrite_cache: + start = time.time() + self.old_features = torch.load(cached_features_file) + + # Legacy cache files have only features, while new cache files + # will have dataset and examples also. + self.features = self.old_features["features"] + self.dataset = self.old_features.get("dataset", None) + self.examples = self.old_features.get("examples", None) + logger.info( + f"Loading features from cached file {cached_features_file} [took %.3f s]", time.time() - start + ) + + if self.dataset is None or self.examples is None: + logger.warning( + f"Deleting cached file {cached_features_file} will allow dataset and examples to be cached in" + " future run" + ) + else: + if mode == Split.dev: + self.examples = self.processor.get_dev_examples(args.data_dir) + else: + self.examples = self.processor.get_train_examples(args.data_dir) + + self.features, self.dataset = squad_convert_examples_to_features( + examples=self.examples, + tokenizer=tokenizer, + max_seq_length=args.max_seq_length, + doc_stride=args.doc_stride, + max_query_length=args.max_query_length, + is_training=mode == Split.train, + threads=args.threads, + return_dataset=dataset_format, + ) + + start = time.time() + torch.save( + {"features": self.features, "dataset": self.dataset, "examples": self.examples}, + cached_features_file, + ) + # ^ This seems to take a lot of time so I want to investigate why and how we can improve. + logger.info( + f"Saving features into cached file {cached_features_file} [took {time.time() - start:.3f} s]" + ) + + def __len__(self): + return len(self.features) + + def __getitem__(self, i) -> Dict[str, torch.Tensor]: + # Convert to Tensors and build dataset + feature = self.features[i] + + input_ids = torch.tensor(feature.input_ids, dtype=torch.long) + attention_mask = torch.tensor(feature.attention_mask, dtype=torch.long) + token_type_ids = torch.tensor(feature.token_type_ids, dtype=torch.long) + cls_index = torch.tensor(feature.cls_index, dtype=torch.long) + p_mask = torch.tensor(feature.p_mask, dtype=torch.float) + is_impossible = torch.tensor(feature.is_impossible, dtype=torch.float) + + inputs = { + "input_ids": input_ids, + "attention_mask": attention_mask, + "token_type_ids": token_type_ids, + } + + if self.args.model_type in ["xlm", "roberta", "distilbert", "camembert"]: + del inputs["token_type_ids"] + + if self.args.model_type in ["xlnet", "xlm"]: + inputs.update({"cls_index": cls_index, "p_mask": p_mask}) + if self.args.version_2_with_negative: + inputs.update({"is_impossible": is_impossible}) + if self.is_language_sensitive: + inputs.update({"langs": (torch.ones(input_ids.shape, dtype=torch.int64) * self.args.lang_id)}) + + if self.mode == Split.train: + start_positions = torch.tensor(feature.start_position, dtype=torch.long) + end_positions = torch.tensor(feature.end_position, dtype=torch.long) + inputs.update({"start_positions": start_positions, "end_positions": end_positions}) + + return inputs diff --git a/wemm/lib/python3.10/site-packages/transformers/data/metrics/__pycache__/__init__.cpython-310.pyc b/wemm/lib/python3.10/site-packages/transformers/data/metrics/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bccad5acf8d00ccbc886cb60835cb028f4a25f2a Binary files /dev/null and b/wemm/lib/python3.10/site-packages/transformers/data/metrics/__pycache__/__init__.cpython-310.pyc differ diff --git a/wemm/lib/python3.10/site-packages/transformers/data/metrics/__pycache__/squad_metrics.cpython-310.pyc b/wemm/lib/python3.10/site-packages/transformers/data/metrics/__pycache__/squad_metrics.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..361210423fb51c2e815aac129384ba32e516e11c Binary files /dev/null and b/wemm/lib/python3.10/site-packages/transformers/data/metrics/__pycache__/squad_metrics.cpython-310.pyc differ diff --git a/wemm/lib/python3.10/site-packages/transformers/data/metrics/squad_metrics.py b/wemm/lib/python3.10/site-packages/transformers/data/metrics/squad_metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..6eea34ad9e81f470c4538189e27ce3e0ab925505 --- /dev/null +++ b/wemm/lib/python3.10/site-packages/transformers/data/metrics/squad_metrics.py @@ -0,0 +1,780 @@ +# Copyright 2020 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" +Very heavily inspired by the official evaluation script for SQuAD version 2.0 which was modified by XLNet authors to +update `find_best_threshold` scripts for SQuAD V2.0 + +In addition to basic functionality, we also compute additional statistics and plot precision-recall curves if an +additional na_prob.json file is provided. This file is expected to map question ID's to the model's predicted +probability that a question is unanswerable. +""" + + +import collections +import json +import math +import re +import string + +from ...models.bert import BasicTokenizer +from ...utils import logging + + +logger = logging.get_logger(__name__) + + +def normalize_answer(s): + """Lower text and remove punctuation, articles and extra whitespace.""" + + def remove_articles(text): + regex = re.compile(r"\b(a|an|the)\b", re.UNICODE) + return re.sub(regex, " ", text) + + def white_space_fix(text): + return " ".join(text.split()) + + def remove_punc(text): + exclude = set(string.punctuation) + return "".join(ch for ch in text if ch not in exclude) + + def lower(text): + return text.lower() + + return white_space_fix(remove_articles(remove_punc(lower(s)))) + + +def get_tokens(s): + if not s: + return [] + return normalize_answer(s).split() + + +def compute_exact(a_gold, a_pred): + return int(normalize_answer(a_gold) == normalize_answer(a_pred)) + + +def compute_f1(a_gold, a_pred): + gold_toks = get_tokens(a_gold) + pred_toks = get_tokens(a_pred) + common = collections.Counter(gold_toks) & collections.Counter(pred_toks) + num_same = sum(common.values()) + if len(gold_toks) == 0 or len(pred_toks) == 0: + # If either is no-answer, then F1 is 1 if they agree, 0 otherwise + return int(gold_toks == pred_toks) + if num_same == 0: + return 0 + precision = 1.0 * num_same / len(pred_toks) + recall = 1.0 * num_same / len(gold_toks) + f1 = (2 * precision * recall) / (precision + recall) + return f1 + + +def get_raw_scores(examples, preds): + """ + Computes the exact and f1 scores from the examples and the model predictions + """ + exact_scores = {} + f1_scores = {} + + for example in examples: + qas_id = example.qas_id + gold_answers = [answer["text"] for answer in example.answers if normalize_answer(answer["text"])] + + if not gold_answers: + # For unanswerable questions, only correct answer is empty string + gold_answers = [""] + + if qas_id not in preds: + print(f"Missing prediction for {qas_id}") + continue + + prediction = preds[qas_id] + exact_scores[qas_id] = max(compute_exact(a, prediction) for a in gold_answers) + f1_scores[qas_id] = max(compute_f1(a, prediction) for a in gold_answers) + + return exact_scores, f1_scores + + +def apply_no_ans_threshold(scores, na_probs, qid_to_has_ans, na_prob_thresh): + new_scores = {} + for qid, s in scores.items(): + pred_na = na_probs[qid] > na_prob_thresh + if pred_na: + new_scores[qid] = float(not qid_to_has_ans[qid]) + else: + new_scores[qid] = s + return new_scores + + +def make_eval_dict(exact_scores, f1_scores, qid_list=None): + if not qid_list: + total = len(exact_scores) + return collections.OrderedDict( + [ + ("exact", 100.0 * sum(exact_scores.values()) / total), + ("f1", 100.0 * sum(f1_scores.values()) / total), + ("total", total), + ] + ) + else: + total = len(qid_list) + return collections.OrderedDict( + [ + ("exact", 100.0 * sum(exact_scores[k] for k in qid_list) / total), + ("f1", 100.0 * sum(f1_scores[k] for k in qid_list) / total), + ("total", total), + ] + ) + + +def merge_eval(main_eval, new_eval, prefix): + for k in new_eval: + main_eval[f"{prefix}_{k}"] = new_eval[k] + + +def find_best_thresh_v2(preds, scores, na_probs, qid_to_has_ans): + num_no_ans = sum(1 for k in qid_to_has_ans if not qid_to_has_ans[k]) + cur_score = num_no_ans + best_score = cur_score + best_thresh = 0.0 + qid_list = sorted(na_probs, key=lambda k: na_probs[k]) + for i, qid in enumerate(qid_list): + if qid not in scores: + continue + if qid_to_has_ans[qid]: + diff = scores[qid] + else: + if preds[qid]: + diff = -1 + else: + diff = 0 + cur_score += diff + if cur_score > best_score: + best_score = cur_score + best_thresh = na_probs[qid] + + has_ans_score, has_ans_cnt = 0, 0 + for qid in qid_list: + if not qid_to_has_ans[qid]: + continue + has_ans_cnt += 1 + + if qid not in scores: + continue + has_ans_score += scores[qid] + + return 100.0 * best_score / len(scores), best_thresh, 1.0 * has_ans_score / has_ans_cnt + + +def find_all_best_thresh_v2(main_eval, preds, exact_raw, f1_raw, na_probs, qid_to_has_ans): + best_exact, exact_thresh, has_ans_exact = find_best_thresh_v2(preds, exact_raw, na_probs, qid_to_has_ans) + best_f1, f1_thresh, has_ans_f1 = find_best_thresh_v2(preds, f1_raw, na_probs, qid_to_has_ans) + main_eval["best_exact"] = best_exact + main_eval["best_exact_thresh"] = exact_thresh + main_eval["best_f1"] = best_f1 + main_eval["best_f1_thresh"] = f1_thresh + main_eval["has_ans_exact"] = has_ans_exact + main_eval["has_ans_f1"] = has_ans_f1 + + +def find_best_thresh(preds, scores, na_probs, qid_to_has_ans): + num_no_ans = sum(1 for k in qid_to_has_ans if not qid_to_has_ans[k]) + cur_score = num_no_ans + best_score = cur_score + best_thresh = 0.0 + qid_list = sorted(na_probs, key=lambda k: na_probs[k]) + for _, qid in enumerate(qid_list): + if qid not in scores: + continue + if qid_to_has_ans[qid]: + diff = scores[qid] + else: + if preds[qid]: + diff = -1 + else: + diff = 0 + cur_score += diff + if cur_score > best_score: + best_score = cur_score + best_thresh = na_probs[qid] + return 100.0 * best_score / len(scores), best_thresh + + +def find_all_best_thresh(main_eval, preds, exact_raw, f1_raw, na_probs, qid_to_has_ans): + best_exact, exact_thresh = find_best_thresh(preds, exact_raw, na_probs, qid_to_has_ans) + best_f1, f1_thresh = find_best_thresh(preds, f1_raw, na_probs, qid_to_has_ans) + + main_eval["best_exact"] = best_exact + main_eval["best_exact_thresh"] = exact_thresh + main_eval["best_f1"] = best_f1 + main_eval["best_f1_thresh"] = f1_thresh + + +def squad_evaluate(examples, preds, no_answer_probs=None, no_answer_probability_threshold=1.0): + qas_id_to_has_answer = {example.qas_id: bool(example.answers) for example in examples} + has_answer_qids = [qas_id for qas_id, has_answer in qas_id_to_has_answer.items() if has_answer] + no_answer_qids = [qas_id for qas_id, has_answer in qas_id_to_has_answer.items() if not has_answer] + + if no_answer_probs is None: + no_answer_probs = {k: 0.0 for k in preds} + + exact, f1 = get_raw_scores(examples, preds) + + exact_threshold = apply_no_ans_threshold( + exact, no_answer_probs, qas_id_to_has_answer, no_answer_probability_threshold + ) + f1_threshold = apply_no_ans_threshold(f1, no_answer_probs, qas_id_to_has_answer, no_answer_probability_threshold) + + evaluation = make_eval_dict(exact_threshold, f1_threshold) + + if has_answer_qids: + has_ans_eval = make_eval_dict(exact_threshold, f1_threshold, qid_list=has_answer_qids) + merge_eval(evaluation, has_ans_eval, "HasAns") + + if no_answer_qids: + no_ans_eval = make_eval_dict(exact_threshold, f1_threshold, qid_list=no_answer_qids) + merge_eval(evaluation, no_ans_eval, "NoAns") + + if no_answer_probs: + find_all_best_thresh(evaluation, preds, exact, f1, no_answer_probs, qas_id_to_has_answer) + + return evaluation + + +def get_final_text(pred_text, orig_text, do_lower_case, verbose_logging=False): + """Project the tokenized prediction back to the original text.""" + + # When we created the data, we kept track of the alignment between original + # (whitespace tokenized) tokens and our WordPiece tokenized tokens. So + # now `orig_text` contains the span of our original text corresponding to the + # span that we predicted. + # + # However, `orig_text` may contain extra characters that we don't want in + # our prediction. + # + # For example, let's say: + # pred_text = steve smith + # orig_text = Steve Smith's + # + # We don't want to return `orig_text` because it contains the extra "'s". + # + # We don't want to return `pred_text` because it's already been normalized + # (the SQuAD eval script also does punctuation stripping/lower casing but + # our tokenizer does additional normalization like stripping accent + # characters). + # + # What we really want to return is "Steve Smith". + # + # Therefore, we have to apply a semi-complicated alignment heuristic between + # `pred_text` and `orig_text` to get a character-to-character alignment. This + # can fail in certain cases in which case we just return `orig_text`. + + def _strip_spaces(text): + ns_chars = [] + ns_to_s_map = collections.OrderedDict() + for i, c in enumerate(text): + if c == " ": + continue + ns_to_s_map[len(ns_chars)] = i + ns_chars.append(c) + ns_text = "".join(ns_chars) + return (ns_text, ns_to_s_map) + + # We first tokenize `orig_text`, strip whitespace from the result + # and `pred_text`, and check if they are the same length. If they are + # NOT the same length, the heuristic has failed. If they are the same + # length, we assume the characters are one-to-one aligned. + tokenizer = BasicTokenizer(do_lower_case=do_lower_case) + + tok_text = " ".join(tokenizer.tokenize(orig_text)) + + start_position = tok_text.find(pred_text) + if start_position == -1: + if verbose_logging: + logger.info(f"Unable to find text: '{pred_text}' in '{orig_text}'") + return orig_text + end_position = start_position + len(pred_text) - 1 + + (orig_ns_text, orig_ns_to_s_map) = _strip_spaces(orig_text) + (tok_ns_text, tok_ns_to_s_map) = _strip_spaces(tok_text) + + if len(orig_ns_text) != len(tok_ns_text): + if verbose_logging: + logger.info(f"Length not equal after stripping spaces: '{orig_ns_text}' vs '{tok_ns_text}'") + return orig_text + + # We then project the characters in `pred_text` back to `orig_text` using + # the character-to-character alignment. + tok_s_to_ns_map = {} + for i, tok_index in tok_ns_to_s_map.items(): + tok_s_to_ns_map[tok_index] = i + + orig_start_position = None + if start_position in tok_s_to_ns_map: + ns_start_position = tok_s_to_ns_map[start_position] + if ns_start_position in orig_ns_to_s_map: + orig_start_position = orig_ns_to_s_map[ns_start_position] + + if orig_start_position is None: + if verbose_logging: + logger.info("Couldn't map start position") + return orig_text + + orig_end_position = None + if end_position in tok_s_to_ns_map: + ns_end_position = tok_s_to_ns_map[end_position] + if ns_end_position in orig_ns_to_s_map: + orig_end_position = orig_ns_to_s_map[ns_end_position] + + if orig_end_position is None: + if verbose_logging: + logger.info("Couldn't map end position") + return orig_text + + output_text = orig_text[orig_start_position : (orig_end_position + 1)] + return output_text + + +def _get_best_indexes(logits, n_best_size): + """Get the n-best logits from a list.""" + index_and_score = sorted(enumerate(logits), key=lambda x: x[1], reverse=True) + + best_indexes = [] + for i in range(len(index_and_score)): + if i >= n_best_size: + break + best_indexes.append(index_and_score[i][0]) + return best_indexes + + +def _compute_softmax(scores): + """Compute softmax probability over raw logits.""" + if not scores: + return [] + + max_score = None + for score in scores: + if max_score is None or score > max_score: + max_score = score + + exp_scores = [] + total_sum = 0.0 + for score in scores: + x = math.exp(score - max_score) + exp_scores.append(x) + total_sum += x + + probs = [] + for score in exp_scores: + probs.append(score / total_sum) + return probs + + +def compute_predictions_logits( + all_examples, + all_features, + all_results, + n_best_size, + max_answer_length, + do_lower_case, + output_prediction_file, + output_nbest_file, + output_null_log_odds_file, + verbose_logging, + version_2_with_negative, + null_score_diff_threshold, + tokenizer, +): + """Write final predictions to the json file and log-odds of null if needed.""" + if output_prediction_file: + logger.info(f"Writing predictions to: {output_prediction_file}") + if output_nbest_file: + logger.info(f"Writing nbest to: {output_nbest_file}") + if output_null_log_odds_file and version_2_with_negative: + logger.info(f"Writing null_log_odds to: {output_null_log_odds_file}") + + example_index_to_features = collections.defaultdict(list) + for feature in all_features: + example_index_to_features[feature.example_index].append(feature) + + unique_id_to_result = {} + for result in all_results: + unique_id_to_result[result.unique_id] = result + + _PrelimPrediction = collections.namedtuple( # pylint: disable=invalid-name + "PrelimPrediction", ["feature_index", "start_index", "end_index", "start_logit", "end_logit"] + ) + + all_predictions = collections.OrderedDict() + all_nbest_json = collections.OrderedDict() + scores_diff_json = collections.OrderedDict() + + for example_index, example in enumerate(all_examples): + features = example_index_to_features[example_index] + + prelim_predictions = [] + # keep track of the minimum score of null start+end of position 0 + score_null = 1000000 # large and positive + min_null_feature_index = 0 # the paragraph slice with min null score + null_start_logit = 0 # the start logit at the slice with min null score + null_end_logit = 0 # the end logit at the slice with min null score + for feature_index, feature in enumerate(features): + result = unique_id_to_result[feature.unique_id] + start_indexes = _get_best_indexes(result.start_logits, n_best_size) + end_indexes = _get_best_indexes(result.end_logits, n_best_size) + # if we could have irrelevant answers, get the min score of irrelevant + if version_2_with_negative: + feature_null_score = result.start_logits[0] + result.end_logits[0] + if feature_null_score < score_null: + score_null = feature_null_score + min_null_feature_index = feature_index + null_start_logit = result.start_logits[0] + null_end_logit = result.end_logits[0] + for start_index in start_indexes: + for end_index in end_indexes: + # We could hypothetically create invalid predictions, e.g., predict + # that the start of the span is in the question. We throw out all + # invalid predictions. + if start_index >= len(feature.tokens): + continue + if end_index >= len(feature.tokens): + continue + if start_index not in feature.token_to_orig_map: + continue + if end_index not in feature.token_to_orig_map: + continue + if not feature.token_is_max_context.get(start_index, False): + continue + if end_index < start_index: + continue + length = end_index - start_index + 1 + if length > max_answer_length: + continue + prelim_predictions.append( + _PrelimPrediction( + feature_index=feature_index, + start_index=start_index, + end_index=end_index, + start_logit=result.start_logits[start_index], + end_logit=result.end_logits[end_index], + ) + ) + if version_2_with_negative: + prelim_predictions.append( + _PrelimPrediction( + feature_index=min_null_feature_index, + start_index=0, + end_index=0, + start_logit=null_start_logit, + end_logit=null_end_logit, + ) + ) + prelim_predictions = sorted(prelim_predictions, key=lambda x: (x.start_logit + x.end_logit), reverse=True) + + _NbestPrediction = collections.namedtuple( # pylint: disable=invalid-name + "NbestPrediction", ["text", "start_logit", "end_logit"] + ) + + seen_predictions = {} + nbest = [] + for pred in prelim_predictions: + if len(nbest) >= n_best_size: + break + feature = features[pred.feature_index] + if pred.start_index > 0: # this is a non-null prediction + tok_tokens = feature.tokens[pred.start_index : (pred.end_index + 1)] + orig_doc_start = feature.token_to_orig_map[pred.start_index] + orig_doc_end = feature.token_to_orig_map[pred.end_index] + orig_tokens = example.doc_tokens[orig_doc_start : (orig_doc_end + 1)] + + tok_text = tokenizer.convert_tokens_to_string(tok_tokens) + + # tok_text = " ".join(tok_tokens) + # + # # De-tokenize WordPieces that have been split off. + # tok_text = tok_text.replace(" ##", "") + # tok_text = tok_text.replace("##", "") + + # Clean whitespace + tok_text = tok_text.strip() + tok_text = " ".join(tok_text.split()) + orig_text = " ".join(orig_tokens) + + final_text = get_final_text(tok_text, orig_text, do_lower_case, verbose_logging) + if final_text in seen_predictions: + continue + + seen_predictions[final_text] = True + else: + final_text = "" + seen_predictions[final_text] = True + + nbest.append(_NbestPrediction(text=final_text, start_logit=pred.start_logit, end_logit=pred.end_logit)) + # if we didn't include the empty option in the n-best, include it + if version_2_with_negative: + if "" not in seen_predictions: + nbest.append(_NbestPrediction(text="", start_logit=null_start_logit, end_logit=null_end_logit)) + + # In very rare edge cases we could only have single null prediction. + # So we just create a nonce prediction in this case to avoid failure. + if len(nbest) == 1: + nbest.insert(0, _NbestPrediction(text="empty", start_logit=0.0, end_logit=0.0)) + + # In very rare edge cases we could have no valid predictions. So we + # just create a nonce prediction in this case to avoid failure. + if not nbest: + nbest.append(_NbestPrediction(text="empty", start_logit=0.0, end_logit=0.0)) + + if len(nbest) < 1: + raise ValueError("No valid predictions") + + total_scores = [] + best_non_null_entry = None + for entry in nbest: + total_scores.append(entry.start_logit + entry.end_logit) + if not best_non_null_entry: + if entry.text: + best_non_null_entry = entry + + probs = _compute_softmax(total_scores) + + nbest_json = [] + for i, entry in enumerate(nbest): + output = collections.OrderedDict() + output["text"] = entry.text + output["probability"] = probs[i] + output["start_logit"] = entry.start_logit + output["end_logit"] = entry.end_logit + nbest_json.append(output) + + if len(nbest_json) < 1: + raise ValueError("No valid predictions") + + if not version_2_with_negative: + all_predictions[example.qas_id] = nbest_json[0]["text"] + else: + # predict "" iff the null score - the score of best non-null > threshold + score_diff = score_null - best_non_null_entry.start_logit - (best_non_null_entry.end_logit) + scores_diff_json[example.qas_id] = score_diff + if score_diff > null_score_diff_threshold: + all_predictions[example.qas_id] = "" + else: + all_predictions[example.qas_id] = best_non_null_entry.text + all_nbest_json[example.qas_id] = nbest_json + + if output_prediction_file: + with open(output_prediction_file, "w") as writer: + writer.write(json.dumps(all_predictions, indent=4) + "\n") + + if output_nbest_file: + with open(output_nbest_file, "w") as writer: + writer.write(json.dumps(all_nbest_json, indent=4) + "\n") + + if output_null_log_odds_file and version_2_with_negative: + with open(output_null_log_odds_file, "w") as writer: + writer.write(json.dumps(scores_diff_json, indent=4) + "\n") + + return all_predictions + + +def compute_predictions_log_probs( + all_examples, + all_features, + all_results, + n_best_size, + max_answer_length, + output_prediction_file, + output_nbest_file, + output_null_log_odds_file, + start_n_top, + end_n_top, + version_2_with_negative, + tokenizer, + verbose_logging, +): + """ + XLNet write prediction logic (more complex than Bert's). Write final predictions to the json file and log-odds of + null if needed. + + Requires utils_squad_evaluate.py + """ + _PrelimPrediction = collections.namedtuple( # pylint: disable=invalid-name + "PrelimPrediction", ["feature_index", "start_index", "end_index", "start_log_prob", "end_log_prob"] + ) + + _NbestPrediction = collections.namedtuple( # pylint: disable=invalid-name + "NbestPrediction", ["text", "start_log_prob", "end_log_prob"] + ) + + logger.info(f"Writing predictions to: {output_prediction_file}") + + example_index_to_features = collections.defaultdict(list) + for feature in all_features: + example_index_to_features[feature.example_index].append(feature) + + unique_id_to_result = {} + for result in all_results: + unique_id_to_result[result.unique_id] = result + + all_predictions = collections.OrderedDict() + all_nbest_json = collections.OrderedDict() + scores_diff_json = collections.OrderedDict() + + for example_index, example in enumerate(all_examples): + features = example_index_to_features[example_index] + + prelim_predictions = [] + # keep track of the minimum score of null start+end of position 0 + score_null = 1000000 # large and positive + + for feature_index, feature in enumerate(features): + result = unique_id_to_result[feature.unique_id] + + cur_null_score = result.cls_logits + + # if we could have irrelevant answers, get the min score of irrelevant + score_null = min(score_null, cur_null_score) + + for i in range(start_n_top): + for j in range(end_n_top): + start_log_prob = result.start_logits[i] + start_index = result.start_top_index[i] + + j_index = i * end_n_top + j + + end_log_prob = result.end_logits[j_index] + end_index = result.end_top_index[j_index] + + # We could hypothetically create invalid predictions, e.g., predict + # that the start of the span is in the question. We throw out all + # invalid predictions. + if start_index >= feature.paragraph_len - 1: + continue + if end_index >= feature.paragraph_len - 1: + continue + + if not feature.token_is_max_context.get(start_index, False): + continue + if end_index < start_index: + continue + length = end_index - start_index + 1 + if length > max_answer_length: + continue + + prelim_predictions.append( + _PrelimPrediction( + feature_index=feature_index, + start_index=start_index, + end_index=end_index, + start_log_prob=start_log_prob, + end_log_prob=end_log_prob, + ) + ) + + prelim_predictions = sorted( + prelim_predictions, key=lambda x: (x.start_log_prob + x.end_log_prob), reverse=True + ) + + seen_predictions = {} + nbest = [] + for pred in prelim_predictions: + if len(nbest) >= n_best_size: + break + feature = features[pred.feature_index] + + # XLNet un-tokenizer + # Let's keep it simple for now and see if we need all this later. + # + # tok_start_to_orig_index = feature.tok_start_to_orig_index + # tok_end_to_orig_index = feature.tok_end_to_orig_index + # start_orig_pos = tok_start_to_orig_index[pred.start_index] + # end_orig_pos = tok_end_to_orig_index[pred.end_index] + # paragraph_text = example.paragraph_text + # final_text = paragraph_text[start_orig_pos: end_orig_pos + 1].strip() + + # Previously used Bert untokenizer + tok_tokens = feature.tokens[pred.start_index : (pred.end_index + 1)] + orig_doc_start = feature.token_to_orig_map[pred.start_index] + orig_doc_end = feature.token_to_orig_map[pred.end_index] + orig_tokens = example.doc_tokens[orig_doc_start : (orig_doc_end + 1)] + tok_text = tokenizer.convert_tokens_to_string(tok_tokens) + + # Clean whitespace + tok_text = tok_text.strip() + tok_text = " ".join(tok_text.split()) + orig_text = " ".join(orig_tokens) + + if hasattr(tokenizer, "do_lower_case"): + do_lower_case = tokenizer.do_lower_case + else: + do_lower_case = tokenizer.do_lowercase_and_remove_accent + + final_text = get_final_text(tok_text, orig_text, do_lower_case, verbose_logging) + + if final_text in seen_predictions: + continue + + seen_predictions[final_text] = True + + nbest.append( + _NbestPrediction(text=final_text, start_log_prob=pred.start_log_prob, end_log_prob=pred.end_log_prob) + ) + + # In very rare edge cases we could have no valid predictions. So we + # just create a nonce prediction in this case to avoid failure. + if not nbest: + nbest.append(_NbestPrediction(text="", start_log_prob=-1e6, end_log_prob=-1e6)) + + total_scores = [] + best_non_null_entry = None + for entry in nbest: + total_scores.append(entry.start_log_prob + entry.end_log_prob) + if not best_non_null_entry: + best_non_null_entry = entry + + probs = _compute_softmax(total_scores) + + nbest_json = [] + for i, entry in enumerate(nbest): + output = collections.OrderedDict() + output["text"] = entry.text + output["probability"] = probs[i] + output["start_log_prob"] = entry.start_log_prob + output["end_log_prob"] = entry.end_log_prob + nbest_json.append(output) + + if len(nbest_json) < 1: + raise ValueError("No valid predictions") + if best_non_null_entry is None: + raise ValueError("No valid predictions") + + score_diff = score_null + scores_diff_json[example.qas_id] = score_diff + # note(zhiliny): always predict best_non_null_entry + # and the evaluation script will search for the best threshold + all_predictions[example.qas_id] = best_non_null_entry.text + + all_nbest_json[example.qas_id] = nbest_json + + with open(output_prediction_file, "w") as writer: + writer.write(json.dumps(all_predictions, indent=4) + "\n") + + with open(output_nbest_file, "w") as writer: + writer.write(json.dumps(all_nbest_json, indent=4) + "\n") + + if version_2_with_negative: + with open(output_null_log_odds_file, "w") as writer: + writer.write(json.dumps(scores_diff_json, indent=4) + "\n") + + return all_predictions diff --git a/wemm/lib/python3.10/site-packages/transformers/data/processors/__pycache__/glue.cpython-310.pyc b/wemm/lib/python3.10/site-packages/transformers/data/processors/__pycache__/glue.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8f461da7583d88d7afeb68e98c7c4a13eb2470d1 Binary files /dev/null and b/wemm/lib/python3.10/site-packages/transformers/data/processors/__pycache__/glue.cpython-310.pyc differ diff --git a/wemm/lib/python3.10/site-packages/transformers/data/processors/__pycache__/squad.cpython-310.pyc b/wemm/lib/python3.10/site-packages/transformers/data/processors/__pycache__/squad.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5887b04719bd7361f296c2a1719dbad5eb2bcd23 Binary files /dev/null and b/wemm/lib/python3.10/site-packages/transformers/data/processors/__pycache__/squad.cpython-310.pyc differ diff --git a/wemm/lib/python3.10/site-packages/transformers/data/processors/__pycache__/utils.cpython-310.pyc b/wemm/lib/python3.10/site-packages/transformers/data/processors/__pycache__/utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1bdf5580aac8e73d6ab1957a532812ac8ec4c776 Binary files /dev/null and b/wemm/lib/python3.10/site-packages/transformers/data/processors/__pycache__/utils.cpython-310.pyc differ diff --git a/wemm/lib/python3.10/site-packages/transformers/data/processors/__pycache__/xnli.cpython-310.pyc b/wemm/lib/python3.10/site-packages/transformers/data/processors/__pycache__/xnli.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9b3581c6922bafb5f40dcc4931b43bd1017aeea5 Binary files /dev/null and b/wemm/lib/python3.10/site-packages/transformers/data/processors/__pycache__/xnli.cpython-310.pyc differ diff --git a/wemm/lib/python3.10/site-packages/transformers/data/processors/squad.py b/wemm/lib/python3.10/site-packages/transformers/data/processors/squad.py new file mode 100644 index 0000000000000000000000000000000000000000..0f8bd2480551158c9916215e43436c8e027dbed0 --- /dev/null +++ b/wemm/lib/python3.10/site-packages/transformers/data/processors/squad.py @@ -0,0 +1,845 @@ +# Copyright 2020 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import json +import os +from functools import partial +from multiprocessing import Pool, cpu_count + +import numpy as np +from tqdm import tqdm + +from ...models.bert.tokenization_bert import whitespace_tokenize +from ...tokenization_utils_base import BatchEncoding, PreTrainedTokenizerBase, TruncationStrategy +from ...utils import is_tf_available, is_torch_available, logging +from .utils import DataProcessor + + +# Store the tokenizers which insert 2 separators tokens +MULTI_SEP_TOKENS_TOKENIZERS_SET = {"roberta", "camembert", "bart", "mpnet"} + + +if is_torch_available(): + import torch + from torch.utils.data import TensorDataset + +if is_tf_available(): + import tensorflow as tf + +logger = logging.get_logger(__name__) + + +def _improve_answer_span(doc_tokens, input_start, input_end, tokenizer, orig_answer_text): + """Returns tokenized answer spans that better match the annotated answer.""" + tok_answer_text = " ".join(tokenizer.tokenize(orig_answer_text)) + + for new_start in range(input_start, input_end + 1): + for new_end in range(input_end, new_start - 1, -1): + text_span = " ".join(doc_tokens[new_start : (new_end + 1)]) + if text_span == tok_answer_text: + return (new_start, new_end) + + return (input_start, input_end) + + +def _check_is_max_context(doc_spans, cur_span_index, position): + """Check if this is the 'max context' doc span for the token.""" + best_score = None + best_span_index = None + for span_index, doc_span in enumerate(doc_spans): + end = doc_span.start + doc_span.length - 1 + if position < doc_span.start: + continue + if position > end: + continue + num_left_context = position - doc_span.start + num_right_context = end - position + score = min(num_left_context, num_right_context) + 0.01 * doc_span.length + if best_score is None or score > best_score: + best_score = score + best_span_index = span_index + + return cur_span_index == best_span_index + + +def _new_check_is_max_context(doc_spans, cur_span_index, position): + """Check if this is the 'max context' doc span for the token.""" + # if len(doc_spans) == 1: + # return True + best_score = None + best_span_index = None + for span_index, doc_span in enumerate(doc_spans): + end = doc_span["start"] + doc_span["length"] - 1 + if position < doc_span["start"]: + continue + if position > end: + continue + num_left_context = position - doc_span["start"] + num_right_context = end - position + score = min(num_left_context, num_right_context) + 0.01 * doc_span["length"] + if best_score is None or score > best_score: + best_score = score + best_span_index = span_index + + return cur_span_index == best_span_index + + +def _is_whitespace(c): + if c == " " or c == "\t" or c == "\r" or c == "\n" or ord(c) == 0x202F: + return True + return False + + +def squad_convert_example_to_features( + example, max_seq_length, doc_stride, max_query_length, padding_strategy, is_training +): + features = [] + if is_training and not example.is_impossible: + # Get start and end position + start_position = example.start_position + end_position = example.end_position + + # If the answer cannot be found in the text, then skip this example. + actual_text = " ".join(example.doc_tokens[start_position : (end_position + 1)]) + cleaned_answer_text = " ".join(whitespace_tokenize(example.answer_text)) + if actual_text.find(cleaned_answer_text) == -1: + logger.warning(f"Could not find answer: '{actual_text}' vs. '{cleaned_answer_text}'") + return [] + + tok_to_orig_index = [] + orig_to_tok_index = [] + all_doc_tokens = [] + for i, token in enumerate(example.doc_tokens): + orig_to_tok_index.append(len(all_doc_tokens)) + if tokenizer.__class__.__name__ in [ + "RobertaTokenizer", + "LongformerTokenizer", + "BartTokenizer", + "RobertaTokenizerFast", + "LongformerTokenizerFast", + "BartTokenizerFast", + ]: + sub_tokens = tokenizer.tokenize(token, add_prefix_space=True) + else: + sub_tokens = tokenizer.tokenize(token) + for sub_token in sub_tokens: + tok_to_orig_index.append(i) + all_doc_tokens.append(sub_token) + + if is_training and not example.is_impossible: + tok_start_position = orig_to_tok_index[example.start_position] + if example.end_position < len(example.doc_tokens) - 1: + tok_end_position = orig_to_tok_index[example.end_position + 1] - 1 + else: + tok_end_position = len(all_doc_tokens) - 1 + + (tok_start_position, tok_end_position) = _improve_answer_span( + all_doc_tokens, tok_start_position, tok_end_position, tokenizer, example.answer_text + ) + + spans = [] + + truncated_query = tokenizer.encode( + example.question_text, add_special_tokens=False, truncation=True, max_length=max_query_length + ) + + # Tokenizers who insert 2 SEP tokens in-between & need to have special handling + # in the way they compute mask of added tokens. + tokenizer_type = type(tokenizer).__name__.replace("Tokenizer", "").lower() + sequence_added_tokens = ( + tokenizer.model_max_length - tokenizer.max_len_single_sentence + 1 + if tokenizer_type in MULTI_SEP_TOKENS_TOKENIZERS_SET + else tokenizer.model_max_length - tokenizer.max_len_single_sentence + ) + sequence_pair_added_tokens = tokenizer.model_max_length - tokenizer.max_len_sentences_pair + + span_doc_tokens = all_doc_tokens + while len(spans) * doc_stride < len(all_doc_tokens): + # Define the side we want to truncate / pad and the text/pair sorting + if tokenizer.padding_side == "right": + texts = truncated_query + pairs = span_doc_tokens + truncation = TruncationStrategy.ONLY_SECOND.value + else: + texts = span_doc_tokens + pairs = truncated_query + truncation = TruncationStrategy.ONLY_FIRST.value + + encoded_dict = tokenizer.encode_plus( # TODO(thom) update this logic + texts, + pairs, + truncation=truncation, + padding=padding_strategy, + max_length=max_seq_length, + return_overflowing_tokens=True, + stride=max_seq_length - doc_stride - len(truncated_query) - sequence_pair_added_tokens, + return_token_type_ids=True, + ) + + paragraph_len = min( + len(all_doc_tokens) - len(spans) * doc_stride, + max_seq_length - len(truncated_query) - sequence_pair_added_tokens, + ) + + if tokenizer.pad_token_id in encoded_dict["input_ids"]: + if tokenizer.padding_side == "right": + non_padded_ids = encoded_dict["input_ids"][: encoded_dict["input_ids"].index(tokenizer.pad_token_id)] + else: + last_padding_id_position = ( + len(encoded_dict["input_ids"]) - 1 - encoded_dict["input_ids"][::-1].index(tokenizer.pad_token_id) + ) + non_padded_ids = encoded_dict["input_ids"][last_padding_id_position + 1 :] + + else: + non_padded_ids = encoded_dict["input_ids"] + + tokens = tokenizer.convert_ids_to_tokens(non_padded_ids) + + token_to_orig_map = {} + for i in range(paragraph_len): + index = len(truncated_query) + sequence_added_tokens + i if tokenizer.padding_side == "right" else i + token_to_orig_map[index] = tok_to_orig_index[len(spans) * doc_stride + i] + + encoded_dict["paragraph_len"] = paragraph_len + encoded_dict["tokens"] = tokens + encoded_dict["token_to_orig_map"] = token_to_orig_map + encoded_dict["truncated_query_with_special_tokens_length"] = len(truncated_query) + sequence_added_tokens + encoded_dict["token_is_max_context"] = {} + encoded_dict["start"] = len(spans) * doc_stride + encoded_dict["length"] = paragraph_len + + spans.append(encoded_dict) + + if "overflowing_tokens" not in encoded_dict or ( + "overflowing_tokens" in encoded_dict and len(encoded_dict["overflowing_tokens"]) == 0 + ): + break + span_doc_tokens = encoded_dict["overflowing_tokens"] + + for doc_span_index in range(len(spans)): + for j in range(spans[doc_span_index]["paragraph_len"]): + is_max_context = _new_check_is_max_context(spans, doc_span_index, doc_span_index * doc_stride + j) + index = ( + j + if tokenizer.padding_side == "left" + else spans[doc_span_index]["truncated_query_with_special_tokens_length"] + j + ) + spans[doc_span_index]["token_is_max_context"][index] = is_max_context + + for span in spans: + # Identify the position of the CLS token + cls_index = span["input_ids"].index(tokenizer.cls_token_id) + + # p_mask: mask with 1 for token than cannot be in the answer (0 for token which can be in an answer) + # Original TF implementation also keep the classification token (set to 0) + p_mask = np.ones_like(span["token_type_ids"]) + if tokenizer.padding_side == "right": + p_mask[len(truncated_query) + sequence_added_tokens :] = 0 + else: + p_mask[-len(span["tokens"]) : -(len(truncated_query) + sequence_added_tokens)] = 0 + + pad_token_indices = np.where(span["input_ids"] == tokenizer.pad_token_id) + special_token_indices = np.asarray( + tokenizer.get_special_tokens_mask(span["input_ids"], already_has_special_tokens=True) + ).nonzero() + + p_mask[pad_token_indices] = 1 + p_mask[special_token_indices] = 1 + + # Set the cls index to 0: the CLS index can be used for impossible answers + p_mask[cls_index] = 0 + + span_is_impossible = example.is_impossible + start_position = 0 + end_position = 0 + if is_training and not span_is_impossible: + # For training, if our document chunk does not contain an annotation + # we throw it out, since there is nothing to predict. + doc_start = span["start"] + doc_end = span["start"] + span["length"] - 1 + out_of_span = False + + if not (tok_start_position >= doc_start and tok_end_position <= doc_end): + out_of_span = True + + if out_of_span: + start_position = cls_index + end_position = cls_index + span_is_impossible = True + else: + if tokenizer.padding_side == "left": + doc_offset = 0 + else: + doc_offset = len(truncated_query) + sequence_added_tokens + + start_position = tok_start_position - doc_start + doc_offset + end_position = tok_end_position - doc_start + doc_offset + + features.append( + SquadFeatures( + span["input_ids"], + span["attention_mask"], + span["token_type_ids"], + cls_index, + p_mask.tolist(), + example_index=0, # Can not set unique_id and example_index here. They will be set after multiple processing. + unique_id=0, + paragraph_len=span["paragraph_len"], + token_is_max_context=span["token_is_max_context"], + tokens=span["tokens"], + token_to_orig_map=span["token_to_orig_map"], + start_position=start_position, + end_position=end_position, + is_impossible=span_is_impossible, + qas_id=example.qas_id, + ) + ) + return features + + +def squad_convert_example_to_features_init(tokenizer_for_convert: PreTrainedTokenizerBase): + global tokenizer + tokenizer = tokenizer_for_convert + + +def squad_convert_examples_to_features( + examples, + tokenizer, + max_seq_length, + doc_stride, + max_query_length, + is_training, + padding_strategy="max_length", + return_dataset=False, + threads=1, + tqdm_enabled=True, +): + """ + Converts a list of examples into a list of features that can be directly given as input to a model. It is + model-dependant and takes advantage of many of the tokenizer's features to create the model's inputs. + + Args: + examples: list of [`~data.processors.squad.SquadExample`] + tokenizer: an instance of a child of [`PreTrainedTokenizer`] + max_seq_length: The maximum sequence length of the inputs. + doc_stride: The stride used when the context is too large and is split across several features. + max_query_length: The maximum length of the query. + is_training: whether to create features for model evaluation or model training. + padding_strategy: Default to "max_length". Which padding strategy to use + return_dataset: Default False. Either 'pt' or 'tf'. + if 'pt': returns a torch.data.TensorDataset, if 'tf': returns a tf.data.Dataset + threads: multiple processing threads. + + + Returns: + list of [`~data.processors.squad.SquadFeatures`] + + Example: + + ```python + processor = SquadV2Processor() + examples = processor.get_dev_examples(data_dir) + + features = squad_convert_examples_to_features( + examples=examples, + tokenizer=tokenizer, + max_seq_length=args.max_seq_length, + doc_stride=args.doc_stride, + max_query_length=args.max_query_length, + is_training=not evaluate, + ) + ```""" + # Defining helper methods + features = [] + + threads = min(threads, cpu_count()) + with Pool(threads, initializer=squad_convert_example_to_features_init, initargs=(tokenizer,)) as p: + annotate_ = partial( + squad_convert_example_to_features, + max_seq_length=max_seq_length, + doc_stride=doc_stride, + max_query_length=max_query_length, + padding_strategy=padding_strategy, + is_training=is_training, + ) + features = list( + tqdm( + p.imap(annotate_, examples, chunksize=32), + total=len(examples), + desc="convert squad examples to features", + disable=not tqdm_enabled, + ) + ) + + new_features = [] + unique_id = 1000000000 + example_index = 0 + for example_features in tqdm( + features, total=len(features), desc="add example index and unique id", disable=not tqdm_enabled + ): + if not example_features: + continue + for example_feature in example_features: + example_feature.example_index = example_index + example_feature.unique_id = unique_id + new_features.append(example_feature) + unique_id += 1 + example_index += 1 + features = new_features + del new_features + if return_dataset == "pt": + if not is_torch_available(): + raise RuntimeError("PyTorch must be installed to return a PyTorch dataset.") + + # Convert to Tensors and build dataset + all_input_ids = torch.tensor([f.input_ids for f in features], dtype=torch.long) + all_attention_masks = torch.tensor([f.attention_mask for f in features], dtype=torch.long) + all_token_type_ids = torch.tensor([f.token_type_ids for f in features], dtype=torch.long) + all_cls_index = torch.tensor([f.cls_index for f in features], dtype=torch.long) + all_p_mask = torch.tensor([f.p_mask for f in features], dtype=torch.float) + all_is_impossible = torch.tensor([f.is_impossible for f in features], dtype=torch.float) + + if not is_training: + all_feature_index = torch.arange(all_input_ids.size(0), dtype=torch.long) + dataset = TensorDataset( + all_input_ids, all_attention_masks, all_token_type_ids, all_feature_index, all_cls_index, all_p_mask + ) + else: + all_start_positions = torch.tensor([f.start_position for f in features], dtype=torch.long) + all_end_positions = torch.tensor([f.end_position for f in features], dtype=torch.long) + dataset = TensorDataset( + all_input_ids, + all_attention_masks, + all_token_type_ids, + all_start_positions, + all_end_positions, + all_cls_index, + all_p_mask, + all_is_impossible, + ) + + return features, dataset + elif return_dataset == "tf": + if not is_tf_available(): + raise RuntimeError("TensorFlow must be installed to return a TensorFlow dataset.") + + def gen(): + for i, ex in enumerate(features): + if ex.token_type_ids is None: + yield ( + { + "input_ids": ex.input_ids, + "attention_mask": ex.attention_mask, + "feature_index": i, + "qas_id": ex.qas_id, + }, + { + "start_positions": ex.start_position, + "end_positions": ex.end_position, + "cls_index": ex.cls_index, + "p_mask": ex.p_mask, + "is_impossible": ex.is_impossible, + }, + ) + else: + yield ( + { + "input_ids": ex.input_ids, + "attention_mask": ex.attention_mask, + "token_type_ids": ex.token_type_ids, + "feature_index": i, + "qas_id": ex.qas_id, + }, + { + "start_positions": ex.start_position, + "end_positions": ex.end_position, + "cls_index": ex.cls_index, + "p_mask": ex.p_mask, + "is_impossible": ex.is_impossible, + }, + ) + + # Why have we split the batch into a tuple? PyTorch just has a list of tensors. + if "token_type_ids" in tokenizer.model_input_names: + train_types = ( + { + "input_ids": tf.int32, + "attention_mask": tf.int32, + "token_type_ids": tf.int32, + "feature_index": tf.int64, + "qas_id": tf.string, + }, + { + "start_positions": tf.int64, + "end_positions": tf.int64, + "cls_index": tf.int64, + "p_mask": tf.int32, + "is_impossible": tf.int32, + }, + ) + + train_shapes = ( + { + "input_ids": tf.TensorShape([None]), + "attention_mask": tf.TensorShape([None]), + "token_type_ids": tf.TensorShape([None]), + "feature_index": tf.TensorShape([]), + "qas_id": tf.TensorShape([]), + }, + { + "start_positions": tf.TensorShape([]), + "end_positions": tf.TensorShape([]), + "cls_index": tf.TensorShape([]), + "p_mask": tf.TensorShape([None]), + "is_impossible": tf.TensorShape([]), + }, + ) + else: + train_types = ( + {"input_ids": tf.int32, "attention_mask": tf.int32, "feature_index": tf.int64, "qas_id": tf.string}, + { + "start_positions": tf.int64, + "end_positions": tf.int64, + "cls_index": tf.int64, + "p_mask": tf.int32, + "is_impossible": tf.int32, + }, + ) + + train_shapes = ( + { + "input_ids": tf.TensorShape([None]), + "attention_mask": tf.TensorShape([None]), + "feature_index": tf.TensorShape([]), + "qas_id": tf.TensorShape([]), + }, + { + "start_positions": tf.TensorShape([]), + "end_positions": tf.TensorShape([]), + "cls_index": tf.TensorShape([]), + "p_mask": tf.TensorShape([None]), + "is_impossible": tf.TensorShape([]), + }, + ) + + return tf.data.Dataset.from_generator(gen, train_types, train_shapes) + else: + return features + + +class SquadProcessor(DataProcessor): + """ + Processor for the SQuAD data set. overridden by SquadV1Processor and SquadV2Processor, used by the version 1.1 and + version 2.0 of SQuAD, respectively. + """ + + train_file = None + dev_file = None + + def _get_example_from_tensor_dict(self, tensor_dict, evaluate=False): + if not evaluate: + answer = tensor_dict["answers"]["text"][0].numpy().decode("utf-8") + answer_start = tensor_dict["answers"]["answer_start"][0].numpy() + answers = [] + else: + answers = [ + {"answer_start": start.numpy(), "text": text.numpy().decode("utf-8")} + for start, text in zip(tensor_dict["answers"]["answer_start"], tensor_dict["answers"]["text"]) + ] + + answer = None + answer_start = None + + return SquadExample( + qas_id=tensor_dict["id"].numpy().decode("utf-8"), + question_text=tensor_dict["question"].numpy().decode("utf-8"), + context_text=tensor_dict["context"].numpy().decode("utf-8"), + answer_text=answer, + start_position_character=answer_start, + title=tensor_dict["title"].numpy().decode("utf-8"), + answers=answers, + ) + + def get_examples_from_dataset(self, dataset, evaluate=False): + """ + Creates a list of [`~data.processors.squad.SquadExample`] using a TFDS dataset. + + Args: + dataset: The tfds dataset loaded from *tensorflow_datasets.load("squad")* + evaluate: Boolean specifying if in evaluation mode or in training mode + + Returns: + List of SquadExample + + Examples: + + ```python + >>> import tensorflow_datasets as tfds + + >>> dataset = tfds.load("squad") + + >>> training_examples = get_examples_from_dataset(dataset, evaluate=False) + >>> evaluation_examples = get_examples_from_dataset(dataset, evaluate=True) + ```""" + + if evaluate: + dataset = dataset["validation"] + else: + dataset = dataset["train"] + + examples = [] + for tensor_dict in tqdm(dataset): + examples.append(self._get_example_from_tensor_dict(tensor_dict, evaluate=evaluate)) + + return examples + + def get_train_examples(self, data_dir, filename=None): + """ + Returns the training examples from the data directory. + + Args: + data_dir: Directory containing the data files used for training and evaluating. + filename: None by default, specify this if the training file has a different name than the original one + which is `train-v1.1.json` and `train-v2.0.json` for squad versions 1.1 and 2.0 respectively. + + """ + if data_dir is None: + data_dir = "" + + if self.train_file is None: + raise ValueError("SquadProcessor should be instantiated via SquadV1Processor or SquadV2Processor") + + with open( + os.path.join(data_dir, self.train_file if filename is None else filename), "r", encoding="utf-8" + ) as reader: + input_data = json.load(reader)["data"] + return self._create_examples(input_data, "train") + + def get_dev_examples(self, data_dir, filename=None): + """ + Returns the evaluation example from the data directory. + + Args: + data_dir: Directory containing the data files used for training and evaluating. + filename: None by default, specify this if the evaluation file has a different name than the original one + which is `dev-v1.1.json` and `dev-v2.0.json` for squad versions 1.1 and 2.0 respectively. + """ + if data_dir is None: + data_dir = "" + + if self.dev_file is None: + raise ValueError("SquadProcessor should be instantiated via SquadV1Processor or SquadV2Processor") + + with open( + os.path.join(data_dir, self.dev_file if filename is None else filename), "r", encoding="utf-8" + ) as reader: + input_data = json.load(reader)["data"] + return self._create_examples(input_data, "dev") + + def _create_examples(self, input_data, set_type): + is_training = set_type == "train" + examples = [] + for entry in tqdm(input_data): + title = entry["title"] + for paragraph in entry["paragraphs"]: + context_text = paragraph["context"] + for qa in paragraph["qas"]: + qas_id = qa["id"] + question_text = qa["question"] + start_position_character = None + answer_text = None + answers = [] + + is_impossible = qa.get("is_impossible", False) + if not is_impossible: + if is_training: + answer = qa["answers"][0] + answer_text = answer["text"] + start_position_character = answer["answer_start"] + else: + answers = qa["answers"] + + example = SquadExample( + qas_id=qas_id, + question_text=question_text, + context_text=context_text, + answer_text=answer_text, + start_position_character=start_position_character, + title=title, + is_impossible=is_impossible, + answers=answers, + ) + examples.append(example) + return examples + + +class SquadV1Processor(SquadProcessor): + train_file = "train-v1.1.json" + dev_file = "dev-v1.1.json" + + +class SquadV2Processor(SquadProcessor): + train_file = "train-v2.0.json" + dev_file = "dev-v2.0.json" + + +class SquadExample: + """ + A single training/test example for the Squad dataset, as loaded from disk. + + Args: + qas_id: The example's unique identifier + question_text: The question string + context_text: The context string + answer_text: The answer string + start_position_character: The character position of the start of the answer + title: The title of the example + answers: None by default, this is used during evaluation. Holds answers as well as their start positions. + is_impossible: False by default, set to True if the example has no possible answer. + """ + + def __init__( + self, + qas_id, + question_text, + context_text, + answer_text, + start_position_character, + title, + answers=[], + is_impossible=False, + ): + self.qas_id = qas_id + self.question_text = question_text + self.context_text = context_text + self.answer_text = answer_text + self.title = title + self.is_impossible = is_impossible + self.answers = answers + + self.start_position, self.end_position = 0, 0 + + doc_tokens = [] + char_to_word_offset = [] + prev_is_whitespace = True + + # Split on whitespace so that different tokens may be attributed to their original position. + for c in self.context_text: + if _is_whitespace(c): + prev_is_whitespace = True + else: + if prev_is_whitespace: + doc_tokens.append(c) + else: + doc_tokens[-1] += c + prev_is_whitespace = False + char_to_word_offset.append(len(doc_tokens) - 1) + + self.doc_tokens = doc_tokens + self.char_to_word_offset = char_to_word_offset + + # Start and end positions only has a value during evaluation. + if start_position_character is not None and not is_impossible: + self.start_position = char_to_word_offset[start_position_character] + self.end_position = char_to_word_offset[ + min(start_position_character + len(answer_text) - 1, len(char_to_word_offset) - 1) + ] + + +class SquadFeatures: + """ + Single squad example features to be fed to a model. Those features are model-specific and can be crafted from + [`~data.processors.squad.SquadExample`] using the + :method:*~transformers.data.processors.squad.squad_convert_examples_to_features* method. + + Args: + input_ids: Indices of input sequence tokens in the vocabulary. + attention_mask: Mask to avoid performing attention on padding token indices. + token_type_ids: Segment token indices to indicate first and second portions of the inputs. + cls_index: the index of the CLS token. + p_mask: Mask identifying tokens that can be answers vs. tokens that cannot. + Mask with 1 for tokens than cannot be in the answer and 0 for token that can be in an answer + example_index: the index of the example + unique_id: The unique Feature identifier + paragraph_len: The length of the context + token_is_max_context: + List of booleans identifying which tokens have their maximum context in this feature object. If a token + does not have their maximum context in this feature object, it means that another feature object has more + information related to that token and should be prioritized over this feature for that token. + tokens: list of tokens corresponding to the input ids + token_to_orig_map: mapping between the tokens and the original text, needed in order to identify the answer. + start_position: start of the answer token index + end_position: end of the answer token index + encoding: optionally store the BatchEncoding with the fast-tokenizer alignment methods. + """ + + def __init__( + self, + input_ids, + attention_mask, + token_type_ids, + cls_index, + p_mask, + example_index, + unique_id, + paragraph_len, + token_is_max_context, + tokens, + token_to_orig_map, + start_position, + end_position, + is_impossible, + qas_id: str = None, + encoding: BatchEncoding = None, + ): + self.input_ids = input_ids + self.attention_mask = attention_mask + self.token_type_ids = token_type_ids + self.cls_index = cls_index + self.p_mask = p_mask + + self.example_index = example_index + self.unique_id = unique_id + self.paragraph_len = paragraph_len + self.token_is_max_context = token_is_max_context + self.tokens = tokens + self.token_to_orig_map = token_to_orig_map + + self.start_position = start_position + self.end_position = end_position + self.is_impossible = is_impossible + self.qas_id = qas_id + + self.encoding = encoding + + +class SquadResult: + """ + Constructs a SquadResult which can be used to evaluate a model's output on the SQuAD dataset. + + Args: + unique_id: The unique identifier corresponding to that example. + start_logits: The logits corresponding to the start of the answer + end_logits: The logits corresponding to the end of the answer + """ + + def __init__(self, unique_id, start_logits, end_logits, start_top_index=None, end_top_index=None, cls_logits=None): + self.start_logits = start_logits + self.end_logits = end_logits + self.unique_id = unique_id + + if start_top_index: + self.start_top_index = start_top_index + self.end_top_index = end_top_index + self.cls_logits = cls_logits diff --git a/wemm/lib/python3.10/site-packages/transformers/kernels/deformable_detr/ms_deform_attn.h b/wemm/lib/python3.10/site-packages/transformers/kernels/deformable_detr/ms_deform_attn.h new file mode 100644 index 0000000000000000000000000000000000000000..119b1fa317d1e5fcfb61a4837e560e9248db05f3 --- /dev/null +++ b/wemm/lib/python3.10/site-packages/transformers/kernels/deformable_detr/ms_deform_attn.h @@ -0,0 +1,61 @@ +/*! +************************************************************************************************** +* Deformable DETR +* Copyright (c) 2020 SenseTime. All Rights Reserved. +* Licensed under the Apache License, Version 2.0 [see LICENSE for details] +************************************************************************************************** +* Modified from https://github.com/chengdazhi/Deformable-Convolution-V2-PyTorch/tree/pytorch_1.0.0 +************************************************************************************************** +*/ + +#pragma once + +#include "cpu/ms_deform_attn_cpu.h" + +#ifdef WITH_CUDA +#include "cuda/ms_deform_attn_cuda.h" +#endif + + +at::Tensor +ms_deform_attn_forward( + const at::Tensor &value, + const at::Tensor &spatial_shapes, + const at::Tensor &level_start_index, + const at::Tensor &sampling_loc, + const at::Tensor &attn_weight, + const int im2col_step) +{ + if (value.type().is_cuda()) + { +#ifdef WITH_CUDA + return ms_deform_attn_cuda_forward( + value, spatial_shapes, level_start_index, sampling_loc, attn_weight, im2col_step); +#else + AT_ERROR("Not compiled with GPU support"); +#endif + } + AT_ERROR("Not implemented on the CPU"); +} + +std::vector +ms_deform_attn_backward( + const at::Tensor &value, + const at::Tensor &spatial_shapes, + const at::Tensor &level_start_index, + const at::Tensor &sampling_loc, + const at::Tensor &attn_weight, + const at::Tensor &grad_output, + const int im2col_step) +{ + if (value.type().is_cuda()) + { +#ifdef WITH_CUDA + return ms_deform_attn_cuda_backward( + value, spatial_shapes, level_start_index, sampling_loc, attn_weight, grad_output, im2col_step); +#else + AT_ERROR("Not compiled with GPU support"); +#endif + } + AT_ERROR("Not implemented on the CPU"); +} diff --git a/wemm/lib/python3.10/site-packages/transformers/kernels/mra/cuda_kernel.cu b/wemm/lib/python3.10/site-packages/transformers/kernels/mra/cuda_kernel.cu new file mode 100644 index 0000000000000000000000000000000000000000..87ed89052873813153786bd416a981d3e5279af9 --- /dev/null +++ b/wemm/lib/python3.10/site-packages/transformers/kernels/mra/cuda_kernel.cu @@ -0,0 +1,383 @@ +#include "cuda_kernel.h" + +////////////////////////////////////////////////////////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////////////////////////// + +__global__ void index_max_cuda_kernel( + float *index_vals, // [batch_size, 32, num_block] + int *indices, // [batch_size, num_block] + float *max_vals, // [batch_size, A_num_block * 32] + float *max_vals_scatter, // [batch_size, 32, num_block] + long batch_size, + long A_num_block, + long B_num_block, + long num_block +) { + + long batch_idx = blockIdx.x; + + long thread_idx = threadIdx.x; + long num_thread = blockDim.x; + + extern __shared__ float buffer[]; + int *max_buffer = (int*)buffer; + + for (int i = 0; i < A_num_block * 32; i = i + num_thread) { + int idx = i + thread_idx; + if (idx < A_num_block * 32) { + max_buffer[idx] = -1e8; + } + } + __syncthreads(); + + int *indices_pt = &indices[batch_idx * num_block]; + float *index_vals_pt = &index_vals[batch_idx * num_block * 32]; + + for (int idx_start = 0; idx_start < 32 * num_block; idx_start = idx_start + num_thread) { + int idx = idx_start + thread_idx; + int A_block_idx = indices_pt[idx % num_block] / B_num_block; + atomicMax(&max_buffer[A_block_idx * 32 + idx / num_block], (int)(index_vals_pt[idx] * 1000)); + } + __syncthreads(); + + float *max_vals_pt = &max_vals[batch_idx * A_num_block * 32]; + for (int i = 0; i < A_num_block * 32; i = i + num_thread) { + int idx = i + thread_idx; + if (idx < A_num_block * 32) { + max_vals_pt[idx] = (float)max_buffer[idx] / 1000.; + } + } + + float *max_vals_scatter_pt = &max_vals_scatter[batch_idx * num_block * 32]; + for (int idx_start = 0; idx_start < 32 * num_block; idx_start = idx_start + num_thread) { + int idx = idx_start + thread_idx; + int A_block_idx = indices_pt[idx % num_block] / B_num_block; + max_vals_scatter_pt[idx] = (float)max_buffer[A_block_idx * 32 + idx / num_block] / 1000.; + } + +} + +__global__ void mm_to_sparse_cuda_kernel( + float *dense_A, // [batch_size, A_num_block, dim, 32] + float *dense_B, // [batch_size, B_num_block, dim, 32] + int *indices, // [batch_size, num_block] + float *sparse_C, // [batch_size, num_block, 32, 32] + long batch_size, + long A_num_block, + long B_num_block, + long dim, + long num_block +) { + + long batch_idx = blockIdx.y; + long block_idx = blockIdx.x * blockDim.y + threadIdx.y; + + long thread_idx = threadIdx.x; + + __shared__ float buffer[4096]; + float *A_buffer = &buffer[threadIdx.y * 1024]; // [2, 8, 32] + float *B_buffer = &buffer[threadIdx.y * 1024 + 512]; // [2, 8, 32] + + long batch_idx__block_idx = batch_idx * num_block + block_idx; + + long AB_block_idx = indices[batch_idx__block_idx]; + float *dense_A_pt = &dense_A[(batch_idx * A_num_block + AB_block_idx / B_num_block) * dim * 32]; + float *dense_B_pt = &dense_B[(batch_idx * B_num_block + AB_block_idx % B_num_block) * dim * 32]; + + int reg_1_idx = thread_idx / 8; // [0000000011111111222222223333333344444444555555556666666677777777] + int reg_2_idx = thread_idx % 8; // [0123456701234567012345670123456701234567012345670123456701234567] + + float reg_1[8]; + float reg_2[8]; + + float reg_array[16] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; + + #pragma unroll + for (int i = 0; i < 4; i++) { + A_buffer[i * 64 + thread_idx] = dense_A_pt[i * 64 + thread_idx]; + B_buffer[i * 64 + thread_idx] = dense_B_pt[i * 64 + thread_idx]; + } + + __syncthreads(); + + #pragma unroll + for (int i = 0; i < 4; i++) { + reg_1[i] = A_buffer[reg_1_idx * 4 + i]; + reg_2[i] = B_buffer[reg_2_idx * 4 + i]; + } + + for (int dim_stride = 1; dim_stride < (dim / 8); dim_stride++) { + + #pragma unroll + for (int i = 0; i < 4; i++) { + A_buffer[(dim_stride % 2) * 256 + i * 64 + thread_idx] = dense_A_pt[dim_stride * 256 + i * 64 + thread_idx]; + B_buffer[(dim_stride % 2) * 256 + i * 64 + thread_idx] = dense_B_pt[dim_stride * 256 + i * 64 + thread_idx]; + } + + #pragma unroll + for (int mini_dim_idx = 1; mini_dim_idx < 8; mini_dim_idx++) { + #pragma unroll + for (int i = 0; i < 4; i++) { + reg_1[(mini_dim_idx % 2) * 4 + i] = A_buffer[((dim_stride - 1) % 2) * 256 + mini_dim_idx * 32 + reg_1_idx * 4 + i]; + reg_2[(mini_dim_idx % 2) * 4 + i] = B_buffer[((dim_stride - 1) % 2) * 256 + mini_dim_idx * 32 + reg_2_idx * 4 + i]; + } + #pragma unroll + for (int i = 0; i < 4; i++) { + #pragma unroll + for (int j = 0; j < 4; j++) { + reg_array[i * 4 + j] += reg_1[((mini_dim_idx - 1) % 2) * 4 + i] * reg_2[((mini_dim_idx - 1) % 2) * 4 + j]; + } + } + } + + __syncthreads(); + + #pragma unroll + for (int i = 0; i < 4; i++) { + reg_1[i] = A_buffer[(dim_stride % 2) * 256 + reg_1_idx * 4 + i]; + reg_2[i] = B_buffer[(dim_stride % 2) * 256 + reg_2_idx * 4 + i]; + } + + #pragma unroll + for (int i = 0; i < 4; i++) { + #pragma unroll + for (int j = 0; j < 4; j++) { + reg_array[i * 4 + j] += reg_1[4 + i] * reg_2[4 + j]; + } + } + + } + + #pragma unroll + for (int mini_dim_idx = 1; mini_dim_idx < 8; mini_dim_idx++) { + #pragma unroll + for (int i = 0; i < 4; i++) { + reg_1[(mini_dim_idx % 2) * 4 + i] = A_buffer[256 + mini_dim_idx * 32 + reg_1_idx * 4 + i]; + reg_2[(mini_dim_idx % 2) * 4 + i] = B_buffer[256 + mini_dim_idx * 32 + reg_2_idx * 4 + i]; + } + #pragma unroll + for (int i = 0; i < 4; i++) { + #pragma unroll + for (int j = 0; j < 4; j++) { + reg_array[i * 4 + j] += reg_1[((mini_dim_idx - 1) % 2) * 4 + i] * reg_2[((mini_dim_idx - 1) % 2) * 4 + j]; + } + } + } + #pragma unroll + for (int i = 0; i < 4; i++) { + #pragma unroll + for (int j = 0; j < 4; j++) { + reg_array[i * 4 + j] += reg_1[4 + i] * reg_2[4 + j]; + } + } + __syncthreads(); + + float *C_buffer = &buffer[threadIdx.y * 1024]; // [32, 32] + + #pragma unroll + for (int i = 0; i < 4; i++) { + #pragma unroll + for (int j = 0; j < 4; j++) { + C_buffer[(reg_2_idx * 4 + j) * 32 + reg_1_idx * 4 + i] = reg_array[i * 4 + j]; + } + } + __syncthreads(); + + float *sparse_C_pt = &sparse_C[batch_idx__block_idx * 1024]; + + #pragma unroll + for (int i = 0; i < 16; i++) { + sparse_C_pt[i * 64 + thread_idx] = C_buffer[i * 64 + thread_idx]; + } + +} + +__global__ void sparse_dense_mm_cuda_kernel( + float *sparse_A, // [batch_size, num_block, 32, 32] + int *indices, // [batch_size, num_block] + float *dense_B, // [batch_size, B_num_block, dim, 32] + float *dense_C, // [batch_size, A_num_block, dim, 32] + long batch_size, + long A_num_block, + long B_num_block, + long dim, + long num_block +) { + + long batch_idx = blockIdx.y; + long block_idx = blockIdx.x * blockDim.y + threadIdx.y; + + long thread_idx = threadIdx.x; + + __shared__ float buffer[6144]; + float *A_buffer = &buffer[threadIdx.y * 3072]; // [32, 32] + float *B_buffer = &buffer[threadIdx.y * 3072 + 1024]; // [32, 64] + + long batch_idx__block_idx = batch_idx * num_block + block_idx; + + float *sparse_A_pt = &sparse_A[batch_idx__block_idx * 1024]; + #pragma unroll + for (int i = 0; i < 8; i++) { + A_buffer[i * 128 + thread_idx] = sparse_A_pt[i * 128 + thread_idx]; + } + + long AB_block_idx = indices[batch_idx__block_idx]; + float *dense_B_pt = &dense_B[(batch_idx * B_num_block + AB_block_idx % B_num_block) * 32 * dim]; + float *dense_C_pt = &dense_C[(batch_idx * A_num_block + AB_block_idx / B_num_block) * 32 * dim]; + + // [0000000011111111222222223333333344444444555555556666666677777777] + // [0123456701234567012345670123456701234567012345670123456701234567] + int reg_1_idx = thread_idx / 8; + int reg_2_idx = thread_idx % 8; + + float reg_1[8]; + float reg_2[8]; + + float reg_array[16]; + + for (int dim_stride = 0; dim_stride < dim; dim_stride = dim_stride + 64) { + + #pragma unroll + for (int i = 0; i < 16; i++) { + B_buffer[i * 128 + thread_idx] = dense_B_pt[dim_stride * 32 + i * 128 + thread_idx]; + } + + #pragma unroll + for (int i = 0; i < 16; i++) { + reg_array[i] = 0; + } + + __syncthreads(); + + #pragma unroll + for (int i = 0; i < 4; i++) { + reg_1[i] = B_buffer[(reg_1_idx * 4 + i) * 32]; + reg_2[i] = A_buffer[reg_2_idx * 4 + i]; + } + + #pragma unroll + for (int mini_dim_idx = 1; mini_dim_idx < 32; mini_dim_idx++) { + #pragma unroll + for (int i = 0; i < 4; i++) { + reg_1[(mini_dim_idx % 2) * 4 + i] = B_buffer[(reg_1_idx * 4 + i) * 32 + mini_dim_idx]; + reg_2[(mini_dim_idx % 2) * 4 + i] = A_buffer[mini_dim_idx * 32 + reg_2_idx * 4 + i]; + } + #pragma unroll + for (int i = 0; i < 4; i++) { + #pragma unroll + for (int j = 0; j < 4; j++) { + reg_array[i * 4 + j] += reg_1[((mini_dim_idx - 1) % 2) * 4 + i] * reg_2[((mini_dim_idx - 1) % 2) * 4 + j]; + } + } + } + + #pragma unroll + for (int i = 0; i < 4; i++) { + #pragma unroll + for (int j = 0; j < 4; j++) { + reg_array[i * 4 + j] += reg_1[4 + i] * reg_2[4 + j]; + } + } + + __syncthreads(); + + float *C_buffer = &buffer[threadIdx.y * 3072 + 1024]; // [64, 32] + + #pragma unroll + for (int i = 0; i < 4; i++) { + #pragma unroll + for (int j = 0; j < 4; j++) { + C_buffer[(reg_1_idx * 4 + i) * 32 + reg_2_idx * 4 + j] = reg_array[i * 4 + j]; + } + } + __syncthreads(); + + #pragma unroll + for (int i = 0; i < 16; i++) { + atomicAdd(&dense_C_pt[dim_stride * 32 + i * 128 + thread_idx], C_buffer[i * 128 + thread_idx]); + } + __syncthreads(); + + } + +} + + +__global__ void reduce_sum_cuda_kernel( + float *sparse_A, // [batch_size, num_block, 32, 32] + int *indices, // [batch_size, num_block] + float *dense_C, // [batch_size, A_num_block, 32] + long batch_size, + long A_num_block, + long B_num_block, + long num_block +) { + + long batch_idx = blockIdx.y; + long block_idx = blockIdx.x * blockDim.y + threadIdx.y; + + long thread_idx = threadIdx.x; + + long batch_idx__block_idx = batch_idx * num_block + block_idx; + + long AB_block_idx = indices[batch_idx__block_idx]; + float *sparse_A_pt = &sparse_A[batch_idx__block_idx * 1024]; + + float reg_array[16]; + float value = 0; + + #pragma unroll + for (int i = 0; i < 8; i++) { + reg_array[i] = sparse_A_pt[i * 32 + thread_idx]; + } + #pragma unroll + for (int stride = 8; stride < 32; stride = stride + 8) { + #pragma unroll + for (int i = 0; i < 8; i++) { + reg_array[(stride + i) % 16] = sparse_A_pt[(stride + i) * 32 + thread_idx]; + } + #pragma unroll + for (int i = 0; i < 8; i++) { + value = value + reg_array[(stride - 8 + i) % 16]; + } + } + #pragma unroll + for (int i = 0; i < 8; i++) { + value = value + reg_array[8 + i]; + } + + float *dense_C_pt = &dense_C[(batch_idx * A_num_block + AB_block_idx / B_num_block) * 32]; + + atomicAdd(&dense_C_pt[thread_idx], value); + +} + +__global__ void scatter_cuda_kernel( + float *dense_A, // [batch_size, A_num_block, 32] + int *indices, // [batch_size, num_block] + float *sparse_C, // [batch_size, num_block, 32, 32] + long batch_size, + long A_num_block, + long B_num_block, + long num_block +) { + + long batch_idx = blockIdx.y; + long block_idx = blockIdx.x * blockDim.y + threadIdx.y; + + long thread_idx = threadIdx.x; + + long batch_idx__block_idx = batch_idx * num_block + block_idx; + + long AB_block_idx = indices[batch_idx__block_idx]; + float *dense_A_pt = &dense_A[(batch_idx * A_num_block + AB_block_idx / B_num_block) * 32]; + float *sparse_C_pt = &sparse_C[(batch_idx * num_block + block_idx) * 1024]; + + float value = dense_A_pt[thread_idx]; + + #pragma unroll + for (int i = 0; i < 32; i++) { + sparse_C_pt[i * 32 + thread_idx] = value; + } + +} diff --git a/wemm/lib/python3.10/site-packages/transformers/kernels/mra/cuda_kernel.h b/wemm/lib/python3.10/site-packages/transformers/kernels/mra/cuda_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..a95b46f7d159b11851143710034cf80c20aa6bf8 --- /dev/null +++ b/wemm/lib/python3.10/site-packages/transformers/kernels/mra/cuda_kernel.h @@ -0,0 +1,59 @@ + +#define WARP_SIZE 32 +#define FULL_MASK 0xffffffff +#define OPTIMAL_THREADS 256 + +__global__ void index_max_cuda_kernel( + float *index_vals, // [batch_size, 32, num_block] + int *indices, // [batch_size, num_block] + float *max_vals, // [batch_size, A_num_block * 32] + float *max_vals_scatter, // [batch_size, 32, num_block] + long batch_size, + long A_num_block, + long B_num_block, + long num_block +); + +__global__ void mm_to_sparse_cuda_kernel( + float *dense_A, // [batch_size, A_num_block, dim, 32] + float *dense_B, // [batch_size, B_num_block, dim, 32] + int *indices, // [batch_size, num_block] + float *sparse_C, // [batch_size, num_block, 32, 32] + long batch_size, + long A_num_block, + long B_num_block, + long dim, + long num_block +); + +__global__ void sparse_dense_mm_cuda_kernel( + float *sparse_A, // [batch_size, num_block, 32, 32] + int *indices, // [batch_size, num_block] + float *dense_B, // [batch_size, B_num_block, dim, 32] + float *dense_C, // [batch_size, A_num_block, dim, 32] + long batch_size, + long A_num_block, + long B_num_block, + long dim, + long num_block +); + +__global__ void reduce_sum_cuda_kernel( + float *sparse_A, // [batch_size, num_block, 32, 32] + int *indices, // [batch_size, num_block] + float *dense_C, // [batch_size, A_num_block, 32] + long batch_size, + long A_num_block, + long B_num_block, + long num_block +); + +__global__ void scatter_cuda_kernel( + float *dense_A, // [batch_size, A_num_block, 32] + int *indices, // [batch_size, num_block] + float *sparse_C, // [batch_size, num_block, 32, 32] + long batch_size, + long A_num_block, + long B_num_block, + long num_block +); diff --git a/wemm/lib/python3.10/site-packages/transformers/models/speecht5/__pycache__/modeling_speecht5.cpython-310.pyc b/wemm/lib/python3.10/site-packages/transformers/models/speecht5/__pycache__/modeling_speecht5.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..33f4de7004ef09cb73b2bda684945a9584de957c --- /dev/null +++ b/wemm/lib/python3.10/site-packages/transformers/models/speecht5/__pycache__/modeling_speecht5.cpython-310.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:96a7e1d4ee97e3d8be4bfc5524e5ed21966902464a43e7874379fbf71dc27d84 +size 110691