Example #1
0
    def length(self, text):
        delim = "THISISASECRETKEYYOUWILLNEVERKNOW"
        text = (text.replace('(', '[')
                    .replace(')', ']'))
        text = (text.replace(self.op, "(")
                    .replace(self.ed, ")"))
        level = 0
        charlimit = 0
        trimtext = []
        for i in text:
            if i == "(" or i == ")" or level == 0:
                if i == "(":
                    level += 1
                elif i == ")":
                    level -= 1
                else:
                    charlimit += 1
                trimtext.append(i)

        trimtext = "".join(trimtext)

        p = subprocess.Popen(["/data/project/nullzerobot/local/bin/swath", "-b", delim, "-u", "u,u"],
                             stdin=subprocess.PIPE,
                             stdout=subprocess.PIPE)
        output = p.communicate(input=trimtext.encode('utf-8'))[0].decode('utf-8')
        text = []
        blacklist = [" ", "\n", "(", ")", "", "\r"]
        for i in output:
            if i in blacklist:
                text.append(delim)
                text.append(i)
                text.append(delim)
            else:
                text.append(i)
        text = "".join(text)
        text = text.replace(delim + delim, delim)
        cnt = 0
        allwords = (list(lre.finditer('^(?!{delim}).*?(?={delim})'.format(delim=delim), text)) +
                    list(lre.finditer('(?<={delim}).*?(?={delim})'.format(delim=delim), text)) +
                    list(lre.finditer('(?<={delim}).*?(?!{delim})$'.format(delim=delim), text)))
        output = []
        for item in allwords:
            if item.group() not in blacklist:
                cnt += 1
                output.append(item.group().replace('[', '(').replace(']', ')'))
        # print cnt, charlimit / 2, charlimit / 12
        cnt = max(cnt, charlimit / 10)
        cnt = min(cnt, charlimit / 2)
        return (cnt, " ".join(output))
Example #2
0
    def dorender(self):
        if self.tabactive == 'page':
            self.content = self.page.get()

        self.pat_before = '~~~#m!'
        self.pat_after = self.pat_before[::-1]
        self.pat = self.pat_before + r'\d+' + self.pat_after

        self.begin_assert = '((?:(?!~~~).)*?)'
        self.begin = '~~~#h!'
        self.begin = self.begin + self.begin_assert + self.begin[::-1]

        self.end = '~~~#e!'

        self.leadlink = lre.lre(r'^[\[\{]+')
        self.traillink = lre.lre(r'[#{].*$')

        self.cnt = 0
        self.text = []
        ptr = 0
        while ptr < len(self.content):
            if self.content[ptr:ptr + 2] == '{{' or self.content[ptr:ptr +
                                                                 2] == '[[':
                self.text.append(self.content[ptr])
                self.text.append(self.pat_before)
                self.text.append(str(self.cnt))
                self.cnt += 1
                self.text.append(self.pat_after)
                self.text.append(self.content[ptr + 1])
                ptr += 2
            else:
                self.text.append(self.content[ptr])
                ptr += 1
        self.text = ''.join(self.text)
        self.content = self.text
        self.rmtag('pre')
        self.rmtag('nowiki')
        self.rmtag('source')
        self.content = lre.sub('(?s)<!--.*?-->', '', self.content)
        matches = list(
            lre.finditer('(?s)(' + self.pat + r')(.*?)(?=[|}\]\n])',
                         self.content))
        links = []
        for match in matches:
            links.append(match.group(2))
        translatedLinks = self.translate(links)
        for i, match in enumerate(matches):
            self.text = self.text.replace(match.group(), translatedLinks[i], 1)
        self.finalize()
Example #3
0
    def dorender(self):
        if self.tabactive == 'page':
            self.content = self.page.get()

        self.pat_before = '~~~#m!'
        self.pat_after = self.pat_before[::-1]
        self.pat = self.pat_before + r'\d+' + self.pat_after

        self.begin_assert = '((?:(?!~~~).)*?)'
        self.begin = '~~~#h!'
        self.begin = self.begin + self.begin_assert + self.begin[::-1]

        self.end = '~~~#e!'

        self.leadlink = lre.lre(r'^[\[\{]+')
        self.traillink = lre.lre(r'[#{].*$')

        self.cnt = 0
        self.text = []
        ptr = 0
        while ptr < len(self.content):
            if self.content[ptr:ptr+2] == '{{' or self.content[ptr:ptr+2] == '[[':
                self.text.append(self.content[ptr])
                self.text.append(self.pat_before)
                self.text.append(str(self.cnt))
                self.cnt += 1
                self.text.append(self.pat_after)
                self.text.append(self.content[ptr + 1])
                ptr += 2
            else:
                self.text.append(self.content[ptr])
                ptr += 1
        self.text = ''.join(self.text)
        self.content = self.text
        self.rmtag('pre')
        self.rmtag('nowiki')
        self.rmtag('source')
        self.content = lre.sub('(?s)<!--.*?-->', '', self.content)
        matches = list(lre.finditer('(?s)(' + self.pat + r')(.*?)(?=[|}\]\n])', self.content))
        links = []
        for match in matches:
            links.append(match.group(2))
        translatedLinks = self.translate(links)
        for i, match in enumerate(matches):
            self.text = self.text.replace(match.group(), translatedLinks[i], 1)
        self.finalize()
Example #4
0
def process(page, config, sources):
    if config.get('disable', False): return

    source = wp.Page(config["source"])
    today = site.getcurrenttime()
    originalText = page.get() if page.exists() else None

    if ("stable" in config and (today - pywikibot.Timestamp.fromISOformat(
                    source.getVersionHistory(total=1)[0][1])).days <
                    int(config["stable"])):
        return

    page.u_elist = []
    deprecated = []
    checkcat = []

    if sources:
        source = sources[source]
        
    text = source.text
    
    if page.namespace() == 828:
        text = lre.sub('(?<!:)[Tt]emplate:', u'แม่แบบ:', text)
    
    for item in config["findText"]:
        if len(item) == 3:
            num, find, replace = item
            regex = False
        elif len(item) == 4:
            num, find, replace, regex = item
        else:
            page.u_elist.append(u"คำเตือน: ข้อความค้นหาและแทนที่อันดับที่ {} มีจำนวนพารามิเตอร์ไม่ถูกต้อง".format(num))
            continue

        if regex:
            newtext = lre.sub(find, replace, text)
        else:
            newtext = text.replace(find, replace)
        if newtext == text and find != replace:
            page.u_elist.append(u"คำเตือน: ไม่เกิดการแทนที่ข้อความที่ {}".format(num))
        text = newtext

    def matchbrace(s, i):
        lv = 0
        for i in xrange(i, len(s)):
            if s[i] == "{": lv += 1
            elif s[i] == "}": lv -= 1
            if lv == 0:
                return i
                # not return i + 1 to avoid index out of range

    for item in config["addParam"]:
        if len(item) == 3:
            num, param, translate = item
        else:
            page.u_elist.append(u"คำเตือน: ข้อความแปลที่ {} มีจำนวนพารามิเตอร์ไม่ถูกต้อง".format(num))
            continue

        lst = []
        for i in lre.finditer(r"\{\{\{\s*" + param + "\s*[\|\}]", text):
            begin, end = i.span()
            end = matchbrace(text, begin)
            lst.append((begin, "begin"))
            lst.append((end, "end"))
        lst = sorted(lst)
        lst.append((sys.maxint, sys.maxint))
        ilst = 0
        out = []
        for i in xrange(len(text)):
            if i == lst[ilst][0]:
                if lst[ilst][1] == "begin":
                    out.append("{{{" + translate + "|")
                else:
                    out.append("}}}")
                    # we should put text[i] before "}}}",
                    # but since text[i] == "}", there is no problem :)
                ilst += 1
            out.append(text[i])
        newtext = "".join(out)
        if newtext == text:
            page.u_elist.append(u"คำเตือน: ไม่เกิดการแปลพารามิเตอร์ที่ {}".format(num))
        text = newtext

    """
    for item in config["obsolete"]:
        if len(item) == 3:
            num, oldParam, newParam = item
            showError = False
        elif len(item) == 4:
            num, oldParam, newParam, showError = item
        else:
            page.u_elist.append(u"คำเตือน: การตรวจสอบพารามิเตอร์ล้าสมัยที่ {} มีจำนวนพารามิเตอร์ไม่ถูกต้อง".format(num))
            continue

        category = wp.Category("Category:" + page.title().replace(":", "") +
                               u" ที่ใช้พารามิเตอร์ " + oldParam)
        checkcat.append(category)
        deprecated.append(u'<includeonly>{{{{#if:{{{{{{{}|}}}}}}|[[{}]]'
                          .format(oldParam, category.title()) +
                          ((u'<span class="error">พารามิเตอร์ {} '
                          u'ล้าสมัยแล้ว โปรดใช้ {} แทนที่</span><br />')
                          .format(oldParam, newParam)
                          if showError else u'') +
                          u'}}</includeonly>')
    text = "".join(deprecated) + text
    """
    #=======
    if page.userName() not in ['^Nullzerobot', 'Nullzerobot', 'Nullzero']:
        page.u_elist.append(u"คำเตือน: ผู้แก้ไขหน้านี้ครั้งสุดท้ายคือ " + page.userName())
    
    if (not page.u_elist) and (text == originalText):
        pywikibot.output((u"ไม่มีการเปลี่ยนแปลงในหน้า {}; "
                          u"ยกเลิกการปรับปรุงและแจ้งเตือน").format(source.title()))
        return
    
    if page.namespace() == 828 and 'wrappers' in text:
        page.u_elist.append(u"คำเตือน: มอดูลนี้มี wrapper")
    
    if debug:
        pywikibot.showDiff(originalText or "", text)
        return

    if config.get("sandbox", False):
        page = wp.Page(page.title() + "/sandbox")

    page.u_text = text
    page.put(text, u"ปรับปรุงหน้าอัตโนมัติโดยบอต", async=True, callback=callback)
Example #5
0
def process(text, page_config):
    global putWithSysop

    params = {}
    for key in conf.seriesKey:
        params[conf.seriesKey[key]] = []

    errorlist = []
    deprecated = []
    checkcat = []
    try:
        for param in lre.pats["param"].finditer(text + "|"):
            param = param.group(1)
            key, dat = param.split("=", 1)
            key = key.strip()
            dat = dat.strip()
            if key in conf.translateKey:
                params[conf.translateKey[key]] = dat
            else:
                num = lre.pats["num"].find(key)
                key = lre.pats["num"].sub("", key)
                if key in conf.seriesKey:
                    params[conf.seriesKey[key]].append((num, dat))
                else:
                    error("unknown parameter", param)
    except:
        wp.error()
        if "source" in params:
            pywikibot.output(u"Error when updating %s" % params["source"])
        else:
            pywikibot.output(u"Error when processing page %s" % page_config)
        return

    if not checkparams(params):
        error("something wrong")
        return

    if "disable" in params and params["disable"] == conf.yes:
        return

    source = wp.Page(params["source"])
    page = wp.Page(params["page"])
    today = site.getcurrenttime()
    originalText = page.get() if page.exists() else None

    if ("stable" in params and (today - pywikibot.Timestamp.fromISOformat(
                    source.getVersionHistory(total=1)[0][1])).days <
                    int(params["stable"])):
        return

    params["notifyuser"] = [lre.pats["user0"].find(x.strip(), 1)
                            for x in params["notifyuser"].split("\n")]
    text = source.get()

    #=======

    for i, (num, sfind) in enumerate(params["find"]):
        newtext = text.replace(parse(sfind), parse(params["replace"][i][1]))
        if newtext == text and sfind != params["replace"][i][1]:
            errorlist.append(u"คำเตือน: ไม่เกิดการแทนที่ข้อความที่ {0}".format(num))
        text = newtext

    def matchbrace(s, i):
        lv = 0
        for i in xrange(i, len(s)):
            if s[i] == "{": lv += 1
            elif s[i] == "}": lv -= 1
            if lv == 0:
                return i
                # not return i + 1 to avoid index out of range

    for irep, (num, sp) in enumerate(params["param"]):
        lst = []
        for i in lre.finditer(r"\{\{\{\s*" + sp + "\s*[\|\}]", text):
            begin, end = i.span()
            end = matchbrace(text, begin)
            lst.append((begin, "begin"))
            lst.append((end, "end"))
        lst = sorted(lst)
        lst.append((sys.maxint, sys.maxint))
        ilst = 0
        out = []
        for i in xrange(len(text)):
            if i == lst[ilst][0]:
                if lst[ilst][1] == "begin":
                    out.append("{{{" + params["translate"][irep][1] + "|")
                else:
                    out.append("}}}")
                    # we should put text[i] before "}}}",
                    # but since text[i] == "}", there is no problem :)
                ilst += 1
            out.append(text[i])
        newtext = "".join(out)
        if newtext == text:
            errorlist.append(u"คำเตือน: ไม่เกิดการแปลพารามิเตอร์ที่ {0}".format(num))
        text = newtext

    for i, (num, sdepr) in enumerate(params["depr"]):
        category = wp.Category("Category:" + page.title().replace(":", "") +
                               u" ที่ใช้พารามิเตอร์ " + sdepr)
        checkcat.append(category)
        deprecated.append(u'<includeonly>{{{{#if:{{{{{{{depr}|}}}}}}|[[{cat}]]'
                          .format(depr=sdepr, cat=category.title()) +
                          ((u'<span class="error">พารามิเตอร์ {depr} '
                          u'ล้าสมัยแล้ว โปรดใช้ {rdepr} แทนที่</span><br />')
                          .format(depr=sdepr, rdepr=params["rdepr"][i][1])
                          if (params["errordepr"][i][1] == conf.yes) else u'') +
                          u'}}</includeonly>')
    text = "".join(deprecated) + text

    #=======

    if (not errorlist) and (text == originalText):
        pywikibot.output(u"ไม่มีการเปลี่ยนแปลงในหน้า %s; "
                         u"ยกเลิกการปรับปรุงและแจ้งเตือน" % source.title())
        return

    if debug:
        pywikibot.showDiff(originalText or "", text)
        return

    if "sandbox" in params and params["sandbox"] == conf.yes:
        page = wp.Page(page.title() + "/sandbox")

    foundError = False

    try:
        page.put(text, u"ปรับปรุงหน้าอัตโนมัติโดยบอต")
    except (pywikibot.LockedPage, pywikibot.PageNotSaved):
        try:
            page.put(text, u"ปรับปรุงหน้าอัตโนมัติโดยบอต", as_group='sysop')
        except:
            foundError = True
    except:
        foundError = True

    if foundError:
        pywikibot.output("<!-- Begin error -->")
        pywikibot.output(text)
        pywikibot.output("<!-- End error -->")
        errorlist.append(u"ผิดพลาด: ไม่เกิดการเขียนหน้า <pre>{}</pre>".format(sys.exc_info()[0]))
        wp.error()

    if checkcat:
        time.sleep(30)
        for cat in checkcat:
            if cat.isEmptyCategory():
                errorlist.append(u"[[:%s]] ว่างลงแล้ว "
                                 u"แสดงว่าไม่มีพารามิเตอร์ล้าสมัย "
                                 u"คุณอาจเขียนคู่มือการใช้งานใหม่"
                                 u"และลบการตั้งค่าพารามิเตอร์ล้าสมัยออก" %
                                 cat.title())

    #for user in params["notifyuser"]:
    for user in ["Nullzero"]:
        lnotify.notify("updatePage", wp.User(user).getUserTalkPage(), {
                    "page": page.title(),
                    "error": "".join(map(lambda x: "* " + x + "\n", errorlist)),
                    "warn_module": u"และดู [[:หมวดหมู่:หน้าที่มีสคริปต์ผิดพลาด]] " if # มีเดียวิกิ:Scribunto-common-error-category
                                   page.namespace() == 828 else "",
                    "page_config": page_config,
                    "revision": page.latestRevision(),
                }, u"แจ้งการปรับปรุงหน้าอัตโนมัติ")