Team Ai
Apppublic

David310/Detect_AI-generated_Image

sourceHugging Faceupdated 2y agoView on Hugging Face
4likes
simple_tokenizer.py133 linesDownload Raw Back to clip
1import gzip2import html3import os4from functools import lru_cache5 6import ftfy7import regex as re8 9 10@lru_cache()11def default_bpe():12    return os.path.join(os.path.dirname(os.path.abspath(__file__)), "bpe_simple_vocab_16e6.txt.gz")13 14 15@lru_cache()16def bytes_to_unicode():17    """18    Returns list of utf-8 byte and a corresponding list of unicode strings.19    The reversible bpe codes work on unicode strings.20    This means you need a large # of unicode characters in your vocab if you want to avoid UNKs.21    When you're at something like a 10B token dataset you end up needing around 5K for decent coverage.22    This is a signficant percentage of your normal, say, 32K bpe vocab.23    To avoid that, we want lookup tables between utf-8 bytes and unicode strings.24    And avoids mapping to whitespace/control characters the bpe code barfs on.25    """26    bs = list(range(ord("!"), ord("~")+1))+list(range(ord("¡"), ord("¬")+1))+list(range(ord("®"), ord("ÿ")+1))27    cs = bs[:]28    n = 029    for b in range(2**8):30        if b not in bs:31            bs.append(b)32            cs.append(2**8+n)33            n += 134    cs = [chr(n) for n in cs]35    return dict(zip(bs, cs))36 37 38def get_pairs(word):39    """Return set of symbol pairs in a word.40    Word is represented as tuple of symbols (symbols being variable-length strings).41    """42    pairs = set()43    prev_char = word[0]44    for char in word[1:]:45        pairs.add((prev_char, char))46        prev_char = char47    return pairs48 49 50def basic_clean(text):51    text = ftfy.fix_text(text)52    text = html.unescape(html.unescape(text))53    return text.strip()54 55 56def whitespace_clean(text):57    text = re.sub(r'\s+', ' ', text)58    text = text.strip()59    return text60 61 62class SimpleTokenizer(object):63    def __init__(self, bpe_path: str = default_bpe()):64        self.byte_encoder = bytes_to_unicode()65        self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}66        merges = gzip.open(bpe_path).read().decode("utf-8").split('\n')67        merges = merges[1:49152-256-2+1]68        merges = [tuple(merge.split()) for merge in merges]69        vocab = list(bytes_to_unicode().values())70        vocab = vocab + [v+'</w>' for v in vocab]71        for merge in merges:72            vocab.append(''.join(merge))73        vocab.extend(['<|startoftext|>', '<|endoftext|>'])74        self.encoder = dict(zip(vocab, range(len(vocab))))75        self.decoder = {v: k for k, v in self.encoder.items()}76        self.bpe_ranks = dict(zip(merges, range(len(merges))))77        self.cache = {'<|startoftext|>': '<|startoftext|>', '<|endoftext|>': '<|endoftext|>'}78        self.pat = re.compile(r"""<\|startoftext\|>|<\|endoftext\|>|'s|'t|'re|'ve|'m|'ll|'d|[\p{L}]+|[\p{N}]|[^\s\p{L}\p{N}]+""", re.IGNORECASE)79 80    def bpe(self, token):81        if token in self.cache:82            return self.cache[token]83        word = tuple(token[:-1]) + ( token[-1] + '</w>',)84        pairs = get_pairs(word)85 86        if not pairs:87            return token+'</w>'88 89        while True:90            bigram = min(pairs, key = lambda pair: self.bpe_ranks.get(pair, float('inf')))91            if bigram not in self.bpe_ranks:92                break93            first, second = bigram94            new_word = []95            i = 096            while i < len(word):97                try:98                    j = word.index(first, i)99                    new_word.extend(word[i:j])100                    i = j101                except:102                    new_word.extend(word[i:])103                    break104 105                if word[i] == first and i < len(word)-1 and word[i+1] == second:106                    new_word.append(first+second)107                    i += 2108                else:109                    new_word.append(word[i])110                    i += 1111            new_word = tuple(new_word)112            word = new_word113            if len(word) == 1:114                break115            else:116                pairs = get_pairs(word)117        word = ' '.join(word)118        self.cache[token] = word119        return word120 121    def encode(self, text):122        bpe_tokens = []123        text = whitespace_clean(basic_clean(text)).lower()124        for token in re.findall(self.pat, text):125            token = ''.join(self.byte_encoder[b] for b in token.encode('utf-8'))126            bpe_tokens.extend(self.encoder[bpe_token] for bpe_token in self.bpe(token).split(' '))127        return bpe_tokens128 129    def decode(self, tokens):130        text = ''.join([self.decoder[token] for token in tokens])131        text = bytearray([self.byte_decoder[c] for c in text]).decode('utf-8', errors="replace").replace('</w>', ' ')132        return text133