Χρήστης:Vanished user oiubfdybvyfnkdsd/py/fixdir/basic

Από Βικιλεξικό
Μετάβαση στην πλοήγηση Πήδηση στην αναζήτηση

Χρήστης:Tzatzbt/py/fixdir/elwiktionarystandard

#!/usr/bin/python3
#Δημιουργήθηκε από τον Xoristzatziki στο el.wiktionary.org
#2018

import os, time, re , sys

import importlib.util
pyfilepath = os.path.join(os.path.dirname(os.path.realpath(__file__)), "elwiktionarystandard.py")

spec = importlib.util.spec_from_file_location("adummyname", pyfilepath)
elwiktionarystandard = importlib.util.module_from_spec(spec)
spec.loader.exec_module(elwiktionarystandard)

#from wikiOCPlocal import db, fromonline

#Αρχίζει με κάποιον αριθμό = (δηλαδή το σύμβολο της ισότητας), έχει κάποιο κείμενο, τελειώνει με ίδιο αριθμό = και ίσως με άχρηστο κείμενο
sectionsre = "(?P<AGROUP>=+)\s*?(?P<BGROUP>.+)\s*?(?P=AGROUP)(?P<CGROUP>.*)$"
sectionTFULLre = "(?P<TEMPLSTART>\{\{)(?P<TEMPLFULL>((?P<TEMPNAME>.*?)\|{1}(?P<PARAMS>.*))|(?P<TEMPNAMENOPARAMS>.*?))(?P<TEMPLEND>\}\})$"

translationsre = "(?P<ΤΗΕTABLE>(?P<STARTLINE>\{\{μτφ-αρχή.*?\}\})+?\s*?.*?(?P<ENDLINE>\{\{μτφ-τέλος\}\})+?\s*?)"

LANGSECTIONSTATE_OK = 0
LANGSECTIONSTATE_NO = 1
LANGSECTIONSTATE_SORTERROR = 2
TRANSLATIONS_NOT_IN_EL = 1
TRANSLATIONS_WRONG_SECTION = 2
TRANSLATIONS_WRONG_DEPTH = 4


createsoundsubsection = elwiktionarystandard.createsoundsubsection
get_from_modulesinfiles = elwiktionarystandard.get_from_modulesinfiles
get_languages_from_string = elwiktionarystandard.get_languages_from_string
get_languages_with_sort = elwiktionarystandard.get_languages_with_sort
get_parts_from_string = elwiktionarystandard.get_parts_from_string
get_sortkeymaps_from_string = elwiktionarystandard.get_sortkeymaps_from_string
make_sort_key = elwiktionarystandard.make_sort_key
has_at_least_one_audio = elwiktionarystandard.has_at_least_one_audio
polish_sortkey = elwiktionarystandard.polish_sortkey
fixkleida = elwiktionarystandard.fixkleida
get_a_marker = elwiktionarystandard.get_a_marker
text_from_sections = elwiktionarystandard.text_from_sections
remove_noninline_comments = elwiktionarystandard.remove_noninline_comments

def get_from_modules(thedbfile):
    try:
        #GET FROM specific sqlite3 db
        from wikiOCPlocal import db, fromonline

        with db.wikiDB(thedbfile) as workingdb:
            sortkeyfrommodule, thets, thelns = workingdb.get_lemma_content("Module:Kleida-el")
            languagesfrommodule, thets, thelns = workingdb.get_lemma_content("Module:Languages")
            partsfrommodule, thets, thelns = workingdb.get_lemma_content("Module:PartOfSpeech")
        sortkeymaps = get_sortkeymaps_from_string(sortkeyfrommodule)
        languagesnosort = get_languages_from_string(languagesfrommodule)
        languages = get_languages_with_sort(languagesnosort, sortkeymaps)
        parts = get_parts_from_string(partsfrommodule)
        return sortkeymaps, languages, parts
    except Exception as e:
        print(e)

def get_Sections(pagetitle, wikitext, languages, parts, sortkeymaps):
    '''Επιστρέφει πίνακα με τα περιεχόμενα όλων των ενοτήτων.
    Το κείμενο μπορεί να αναδημιουργηθεί χρησιμοποιώντας τα depth, originaltitle και content.
    depth: περιέχει τον αριθμό των = που χρησιμοποιεί ο τίτλος της ενότητας
    originaltitle: το ακριβές κείμενο στη γραμμή ενότητας
    content: το περιεχόμενο κάτω από τη γραμμή ενότητας
    '''
    if pagetitle.startswith('Πύλη:'):
        return [], '', []
    if wikitext.strip().startswith('{{softredirect'):
        return [], '', []
    #print(pagetitle)
    wikitext, amarker, comments = remove_noninline_comments(wikitext)
    wikitext = fixkleida(wikitext)
    #print(wikitext)
    #print('=====================')
    splittedlines = wikitext.splitlines(True)
    #print('splittedlines',len(splittedlines))
    sections = {}
    #langsections = []
    sectionCounter = 0
    sections[-1] = {'pagename':pagetitle,'garbage':'', 'problems':'',
            'nolang':False, 'unsortedlangs': False, 'fixsectiontitles': '',
            'nosubsections':'', 'changes':'',
            'badheadwords':False, 'badlangsection': False
            }

    sections[0] = {'depth':1, 'title':'', 'originaltitleline':'',
            'langiso':'', 'template':'', 'ispartofspeech' : False,
            'headword':'', 'content':''}
    lastlang = '' #αρχικά δεν έχουμε γλώσσα
    allgarbage = ''
    headword = ''
    linecounter = 0
    problems = ''
    for line in splittedlines:
        knowntemplate = ''
        garbage = ''
        sectionsrematch = re.match(sectionsre,line)

        ispartofspeech = False
        linecounter += 1

        langiso = ''
        if sectionsrematch:
            #new section found
            sectiontitle = ''
            templateparams = ''
            #print(sectionsrematch)
            sectionCounter += 1
            agroup = sectionsrematch.groupdict()['AGROUP'] #τα = που έχει στην αρχή και στο τέλος
            bgroup = sectionsrematch.groupdict()['BGROUP'] #το περιεχόμενο ανάμεσα στα =
            cgroup = sectionsrematch.groupdict()['CGROUP'] #περιεχόμενο μετά τα = που μπορεί να περιέχει επιπλέον = ή άλλα σκουπίδια
            depth = len(agroup) #αριθμός =
            sectiontitle = bgroup.strip()
            #print(sectiontemplate, 'THE TITLE')
            #originaltitleline = line
            garbage = cgroup if cgroup != '\n' else ''
            #Εύρεση είδους ενότητας δεύτερου βαθμού από τον τίτλο της
            #Είτε είναι ενότητα γλώσσας άρα τύπου {{-ΧΧ-}} είτε κάποια από τις άλλες τυπικές ενότητες
            #για την ώρα μόνο οι ενότητες 'Σημειώσεις' και '{{αναφορές}}' μπορούν να είναι ενότητες βάθους 2
            if depth == 2:#υποτίθεται ότι είναι ενότητα γλώσσας ή η ενότητα για το <references> κλπ

                ispartofspeech = False
                #γνωστές ενότητες βάθους 2
                #TODO:use them
                if 'Σημειώσεις' == sectiontitle.strip():
                    sections[-1]['fixsectiontitles'] += ' Σημειώσεις '
                elif 'Αναφορές' == sectiontitle.strip():
                    sections[-1]['fixsectiontitles'] += ' Αναφορές '
                    #print(pagetitle, ' =======Αναφορές ')
                elif 'Πηγές' == sectiontitle.strip():
                    sections[-1]['fixsectiontitles'] += ' Πηγές '
                elif 'παραπομπές' == sectiontitle.strip():
                    sections[-1]['fixsectiontitles'] += ' παραπομπές '
                elif '{{αναφορές}}' == sectiontitle.strip():
                    #TODO:add it
                    pass
                else:
                    #αν δεν είναι σημειώσεις ή αναφορές τότε πρέπει να είναι ενότητα γλώσσας
                    #ελέγχουμε αν είναι του τύπου {{-ΧΧ-}}
                    if sectiontitle.startswith('{{-') and sectiontitle.endswith('-}}') and len(sectiontitle) > 7:
                        #ελέγχουμε αν είναι του τύπου {{-ΧΧ-}}
                        #αφαιρούμε τα {{--}}
                        possiblelang = sectiontitle[3:-3] # θεωρητικά το iso
                        #αν υπάρχει τέτοια γλώσσα
                        if possiblelang in languages:
                            langiso = possiblelang
                            if langiso in ['el', 'gkm', 'grc' ] or (not languages[langiso]['haswiktionary']):
                                headword = "'''{{PAGENAME}}'''"
                            else:
                                headword = '{{τ|' + langiso + '|{{PAGENAME}}}}'

                        else:
                            #δεν υπάρχει το iso
                            garbage += 'Λάθος τίτλος ενότητας βάθους 2:' + sectiontitle
                            sections[-1]['badlangsection'] = True

                    else:#κάποια εσφαλμένη ενότητα βάθους 2, δεν ελέγχω αν είναι γνωστή
                        garbage += 'Λάθος τίτλος ενότητας βάθους 2:' + sectiontitle

            else:
                if depth > 2:#είναι ενότητα βάθους μεγαλύτερου από 2
                    #είτε μέσα σε ενότητα γλώσσας είτε σε εσφαλμένη ενότητα
                    thematch = re.match(sectionTFULLre, sectiontitle)
                    if thematch:#βρήκαμε κάτι
                        if thematch.groupdict()['TEMPNAMENOPARAMS']:
                            #ενότητα η οποία έχει σαν τίτλο κάποιο πρότυπο χωρίς παραμέτρους
                            thetemplate = thematch.groupdict()['TEMPNAMENOPARAMS'].strip()
                            ispartofspeech = (thetemplate in parts)
                            knowntemplate = thetemplate
                        elif thematch.groupdict()['TEMPNAME']:
                            #ενότητα η οποία έχει σαν τίτλο πρότυπο με παραμέτρους
                            #οι παράμετροι αυτή τη στιγμή είναι:
                            #είτε η παράμετρος γλώσσας
                            #είτε αριθμός για χωριστές ενότητες ετυμολόγησης
                            thetemplate = thematch.groupdict()['TEMPNAME'].strip()
                            ispartofspeech = (thetemplate in parts)
                            knowntemplate = thetemplate
                            templateparams = thematch.groupdict()['PARAMS'].strip()
                        else:
                            #ακαθόριστη ενότητα
                            ispartofspeech = False
                    else:
                        #δεν βρέθηκε κάτι
                        ispartofspeech = False
                        garbage += 'Λάθος τίτλος ενότητας βάθους ' + str(depth) + ':' + sectiontitle
            #αφού είναι ενότητα
            #προσθέτουμε νέα ενότητα
            sections[sectionCounter] = {'depth':depth, 'title':sectiontitle,
                    'originaltitleline':line, 'langiso': langiso,
                    'template': knowntemplate, 'ispartofspeech': ispartofspeech,
                    'templateparams':templateparams,
                    'headword':'', 'content':''}

        else:#δεν είναι γραμμή με «σωστά ίσον»
            #είτε ο αριθμός των «ίσον» δεν συμφωνεί
            #είτε είναι το κείμενο που υπάρχει ανάμεσα στις γραμμές ενοτήτων
            #η περίπτωση των διαφορετικών ίσον δεν θα εξεταστεί
            #θα θεωρηθεί ότι αποτελεί κείμενο μέσα σε ενότητα
            #προσθέτουμε το κείμενο στο περιεχόμενο
            sections[sectionCounter]['content'] += line

        allgarbage += garbage
    sections[-1]['garbage'] = allgarbage
    newsections = convert_to_langsections(sections, languages, parts, sortkeymaps)
    return newsections, amarker, comments

def convert_to_langsections(sections, languages, parts, sortkeymaps):
    langsections = {}
    langCounter = 0
    langsections[-1] = sections[-1]
    langsections[0] = {'langsection': sections[0], 'subsections':[]}
    for asection in sorted([x for x in sections if x>0]):
        if sections[asection]['langiso'] != '':
            langCounter += 1
            theiso = sections[asection]['langiso']

            langsections[langCounter] = {'langsection':sections[asection],
            'langsort':languages[theiso]['sort'],
            'subsections':[]}
        else:
            #βρισκόμαστε μέσα σε μία ενότητα γλώσσας
            #φυσικά μπορεί να προηγείται λανθασμένη ενότητα γλώσσας
            #αλλά αυτό είναι άλλο πρόβλημα
            #θεωρούμε ότι όλα ανήκουν σε αυτήν, την προηγούμενη, γλώσσα
            #ακόμα και για ενότητες βάθους 2, όπως το «αναφορές»
            langsections[langCounter]['subsections'].append(sections[asection])
    #check langchanges
    if langCounter<1:
        langsections[-1]['problems'] += 'Χωρίς ενότητα γνωστής γλώσσας\n'
        langsections[-1]['nolang'] = True
    elif langCounter>1:
        langchangeproblem = False
        for xcounter in range(1,langCounter):
            #Μπορεί να μην έχει subsections
            if len(langsections[xcounter]['subsections']):
                if not langsections[xcounter]['subsections'][-1]['content'].endswith('\n\n\n----\n\n'):
                    langchangeproblem = True
            else:
                #print(langsections[xcounter])
                langsections[-1]['nosubsections'] += ' ' + langsections[xcounter]['langsection']['langiso']
                #print(langsections[-1]['pagename'], 'nosubsections')
                if not langsections[xcounter]['langsection']['content'].endswith('\n\n\n----\n\n'):
                    #print("langsections[xcounter]['content']",langsections[xcounter]['content'])
                    langchangeproblem = True
        if langchangeproblem:
            langsections[-1]['problems'] += 'Σφάλμα σε κάποια αλλαγή γλώσσας\n'

        keys = [langsections[x]['langsort'] for x in sorted([x for x in langsections if x>0])]
        if keys != sorted(keys):
            langsections[-1]['problems'] += 'Λάθος ταξινομημένες γλώσσες\n'
            langsections[-1]['unsortedlangs'] = True

    return langsections

def checkforsound(thedbfile):
    '''Requires wikiOCPlocal.fromonline, wikiOCPlocal.db'''
    from wikiOCPlocal import db, fromonline

    head, tail = os.path.split(thedbfile)
    thetitlesfile = os.path.join(head,'fixdir', 'titles_for_sounds.wiki')
    print(thetitlesfile)
    with open(thetitlesfile,'wt', encoding="utf-8") as f:
        f.write('START\n')
    #return
    with db.wikiDB(thedbfile) as workingdb:
        sortkeymaps, languages, parts = get_from_modules(thedbfile)
        print('itering')
        pagesforsounds = []
        for adbrow in workingdb.iter_articles(ns=0):
            #print(adbrow.title)
            try:
                if adbrow.isredirect:
                    continue
                if adbrow.title.startswith('Πύλη:'):
                    continue
                if adbrow.content.startswith('{{διαγραφή'):
                    continue

                pagetitle = adbrow.title
                wikitext = adbrow.content
                #print('get_Sections')
                sections = get_Sections(pagetitle, wikitext, languages, parts, sortkeymaps)
                hassounds = False
                if len(sections[0]['langsections']):
                    langsections = sections[0]['langsections']
                    for section in langsections:
                        sectionlang = langsections[section]['section']['langiso']
                        partiallangogg = sectionlang.title() + "-" + pagetitle
                        langogg = partiallangogg + ".ogg"
                        etymologysection = None
                        soundsection = None
                        noknownsound = True
                        if 'etymologysection' in langsections[section]['section']:
                            etymologysection = langsections[section]['section']['etymologysection']
                            #print('has etymology', sectionlang , etymologysection)
                        else:
                            #print('no etymology', sectionlang)
                            pass
                        if 'soundsection' in langsections[section]['section']:
                            soundsection = langsections[section]['section']['soundsection']
                            #print('has soundsection', sectionlang , soundsection)
                            if partiallangogg in langsections[section]['subsections'][soundsection]['content']:
                                #print('HAS SOME SOUND', sectionlang)
                                noknownsound = False
                            elif "{{ήχος|" in langsections[section]['subsections'][soundsection]['content']:
                                #print('HAS SOME ήχος', sectionlang)
                                noknownsound = False
                            else:
                                #print('HAS soundsection but no known', sectionlang)
                                pass
                        else:
                            #print('no soundsection', sectionlang)
                            pass
                        if noknownsound:
                            if fromonline.fileexistsincommons("File:" + langogg):
                                if pagetitle not in pagesforsounds:
                                    hassounds = True
                    if hassounds:
                        with open(thetitlesfile,'at', encoding="utf-8") as f:
                            f.write(pagetitle + '\n')
                        print(pagetitle)#, sectionlang)

            except Exception as e:
                print(adbrow.title)
                print('exc', e)
                return

def check_audio_files(sections):
    '''Ελέγχει αν στην κάθε ενότητα γλώσσας υπάρχει αρχείο με ήχο. '''
    from wikiOCPlocal import db, fromonline
    pagetitle = sections[-1]['pagename']
    audiolangsadded = []
    for asection in sorted([x for x in sections if x>0]):
        sectionlangiso = sections[asection]['langsection']['langiso']
        partiallangogg = sectionlangiso.title() + "-" + pagetitle
        langogg = partiallangogg + ".ogg"
        #print(langogg)
        etymologysectionindex = -1
        soundsectionindex = -1
        subsectioncounter = 0
        for asubsection in sections[asection]['subsections']:
            if asubsection['template'] == 'ετυμολογία':
                etymologysectionindex = subsectioncounter
            if asubsection['template'] == 'προφορά':
                soundsectionindex = subsectioncounter
            subsectioncounter += 1
        if soundsectionindex>=0:
            if "{{ήχος|" in sections[asection]['subsections'][soundsectionindex]['content']:
                continue
            if langogg in sections[asection]['subsections'][soundsectionindex]['content']:
                continue
            #add the file on top of others
            if fromonline.fileexistsincommons("File:" + langogg):
                sections[asection]['subsections'][soundsectionindex]['content'] = "{{ήχος|" + sectionlangiso + "}}" + "\n" + sections[asection]['subsections'][soundsectionindex]['content']
                audiolangsadded.append(sectionlangiso)
                sections[-1]['changes'] += '\nΠροσθήκη ήχου ' + sectionlangiso
            else:
                continue
        else:
            if fromonline.fileexistsincommons("File:" + langogg):
                soundsection = createsoundsubsection(sectionlangiso)
                if etymologysectionindex == 0:
                    sections[asection]['subsections'].insert(1, soundsection)
                    audiolangsadded.append(sectionlangiso)
                else:
                    sections[asection]['subsections'].insert(0, soundsection)
                    audiolangsadded.append(sectionlangiso)
                sections[-1]['changes'] += '\nΠροσθήκη ενότητας ήχου ' + sectionlangiso
    return audiolangsadded

def fix_end_of_sections(sections):
    end_re = '(?P<STARTRETURNS>\n*?)----(?P<ENDRETURNS>\n*?)$'
    pagename = sections[-1]['pagename']
    if pagename.startswith('Πύλη:'):
        return False
    langsectionsnums = [x for x in sorted(sections) if x > 0]
    changesdone = False

    if len(langsectionsnums) < 1: #No lang sections BAD article
        return False
    lastlangsection = False
    #every langsection has a dict named langsection with content and originaltitleline
    #every subsection is a dict with content and originaltitleline
    for alangsectionnum in range(len(langsectionsnums)+1):
        lastlangsection = (alangsectionnum == len(langsectionsnums))
        oldoriginaltitle = sections[alangsectionnum]['langsection']['originaltitleline']
        oldcontent = sections[alangsectionnum]['langsection']['content']
        if alangsectionnum:#not in the zero section
            sections[alangsectionnum]['langsection']['originaltitleline'] = oldoriginaltitle.strip() + '\n'
            #add a line return
            sections[alangsectionnum]['langsection']['content'] = oldcontent.strip() + '\n'
            #if has usable content add one more line return
            if oldcontent.strip() != '':
                sections[alangsectionnum]['langsection']['content'] += '\n'
        else:#this the zero section
            print('0 section')
            if oldcontent.strip() != '':#has some content
                sections[alangsectionnum]['langsection']['content'] = oldcontent.strip() + '\n'
            else:#no usefull content
                sections[alangsectionnum]['langsection']['content'] = ''
            #originaltitleline is always empty for zero section

        if oldoriginaltitle != sections[alangsectionnum]['langsection']['originaltitleline']:
            changesdone = True
        if oldcontent != sections[alangsectionnum]['langsection']['content']:
            changesdone = True
        lastsubsection = False
        for subsectionnum, asubsectiondict in enumerate(sections[alangsectionnum]['subsections']):
            lastsubsection = (subsectionnum == len(sections[alangsectionnum]['subsections'])-1)
            oldoriginaltitle = asubsectiondict['originaltitleline']
            asubsectiondict['originaltitleline'] = oldoriginaltitle.strip() + '\n'
            if oldoriginaltitle != asubsectiondict['originaltitleline']:
                changesdone = True
            oldcontent = asubsectiondict['content']
            asubsectiondict['content'] = asubsectiondict['content'].strip() + '\n'
            if not (lastsubsection and lastlangsection):#not at the end
                asubsectiondict['content'] += '\n'
            if oldcontent != asubsectiondict['content']:
                changesdone = True
            #if not the last lang section
            #but is the last subsection
            #check change
            if lastsubsection and not (lastlangsection):
                oldorchangedcontent =  asubsectiondict['content']
                match = re.search(end_re, oldorchangedcontent, flags = re.DOTALL)
                if match:
                    #we found a possible good laguage change
                    oldcharnum = 1 + len(match.group('STARTRETURNS')) + len('----') + len(match.group('ENDRETURNS'))
                    asubsectiondict['content'] = oldorchangedcontent[:-oldcharnum] + '\n\n\n----\n\n'
                else:#laguage change not good, adding a new
                    #this will not report the problem if we have "---" instead of "----"
                    asubsectiondict['content'] = oldorchangedcontent.strip() + '\n\n\n----\n\n'
                if oldorchangedcontent != asubsectiondict['content']:
                    changesdone = True

    if changesdone:
        sections[-1]['changes'] += '\nδιορθώθηκαν αλλαγές και κενά'
    return True

def check_lang_in_sections(sections, languages):
    lines = []
    for alangsectionnum in range(len(langsectionsnums)+1):
        langiso = sections[alangsectionnum]['langsection']['langiso']
        for subsectionnum, asubsectiondict in enumerate(sections[alangsectionnum]['subsections']):
            if asubsectiondict['templateparams']:
                params = asubsectiondict['templateparams'].split('|')
                if params[0] == langiso:
                    pass
                elif params[0] in languages:
                    #wrong iso
                    #lines.append
                    sections[-1]['problems'] += 'Σφάλμα γλώσσας στην ενότητα γλώσσας:' + langiso + '\n'

class CheckTranslations:
    def __init__(self, sections, languages):
        self.sections = sections
        self.languages = languages

    def update_translations(self): #only in langsection 1
        pagename = self.sections[-1]['pagename']
        #newlines = []
        if pagename.startswith('Πύλη:'):
            return
        if 1 in self.sections:
            for asubsectiondict in self.sections[1]['subsections']:
                if asubsectiondict['template'] == 'μεταφράσεις':
                    thecontent = asubsectiondict['content']
                    newstring = re.sub(translationsre, self.replace_with_new_table, thecontent, flags = re.DOTALL)
                    if newstring != asubsectiondict['content']:
                        asubsectiondict['content'] = newstring
                        self.sections[-1]['changes'] += '\nΔιορθώσεις σε πίνακα μεταφράσεων'

    def replace_with_new_table(self, matchobj):
        atable = TranslationTable(matchobj.group('ΤΗΕTABLE'), self.languages)
        newlines, badlines, thetablestring = atable.get_correct_table()
        return thetablestring

class TranslationTable:

    translinere =  '^([*]\s*?|<!--\s*?\*\s*?)\{\{(?P<LANGISO>.*?)\}\}\s*?:\s*?\{\{τ\|(?P=LANGISO)\|.*'
    translinerewithlang =  '^([*]\s*?|<!--\s*?\*\s*?)\{\{(?P<LANGISO>.*?)\}\}\s*?:.*'
    def __init__(self, thestring, languages):
        self.thestring = thestring
        self.languages = languages

    def get_lang(self,line):
        #check if has any lang start
        thematch = re.match(self.translinerewithlang, line.strip())
        if thematch:
            lang = thematch.groupdict()['LANGISO']
            if lang in self.languages:
                return lang
        return None

    def get_correct_table(self):
        lines = []
        startline = ''
        middleline = ''
        endline = ''
        for line in self.thestring.splitlines(True):
            if line.startswith('{{μτφ-αρχή'):
                startline = line
            elif line.startswith('{{μτφ-μέση'):
                middleline = line
            elif line.startswith('{{μτφ-τέλος'):
                endline = line
            elif line.strip() == '':
                pass
            else:
                lang = self.get_lang(line)
                if lang:
                    sortstr = self.languages[lang]['sort']
                else:
                    #print("+++++++++++++++++++++", lang, line)
                    sortstr = ''

                lines.append({'line':line,
                    'lang': lang,
                    'sort': sortstr,
                    'visible': not line.strip().startswith('<!--')
                    })
        #print('transl lines',lines)
        goodlines = [x for x in sorted(lines, key=lambda k: k['sort']) if x['sort'] != '']
        unsortedlines = [x for x in lines if x['sort'] != '']
        #print('old-new============================', unsortedlines == goodlines)
        badlines = [x for x in lines if x['sort'] == '']
        #print('badlines',badlines)
        #, key=lambda x: jsonchanges[x]['timestamp']
        thestring = startline
        xcounter = 0
        middlenum = int(len(goodlines) // 2)
        for line in goodlines:
            xcounter += 1
            if xcounter == middlenum:
                thestring += middleline
            thestring += line['line']
        thestring += endline
        if len(badlines):
            thestring += '\n' + '{{μτφ-κατάταξη}}' + '\n'
            for aline in badlines:
                thestring += aline['line']
        return goodlines, badlines, thestring

def is_bad_lemma(sections):
    if '{{μορφοποίηση' in sections[0]['langsection']['content'] or '{{διαγραφή' in sections[0]['langsection']['content']:
        return False
    #print(sections[-1])
    if sections[-1]['nolang'] or sections[-1]['badlangsection'] or sections[-1]['unsortedlangs']:
        #wikitext = '{{μορφοποίηση}}\n' + wikitext
        return True
    return False

def remove_old_polish_key(sections):
    pagename = sections[-1]['pagename']
    if pagename.startswith('Πύλη:'):
        return
    for alangsectionnum in sections:
        if alangsectionnum > 0:
            sectionlangiso = sections[alangsectionnum]['langsection']['langiso']
            if sectionlangiso == 'pl':
                found_a_key = False
                polish_kleida = polish_sortkey(pagename)
                for asubsectiondict in sections[alangsectionnum]['subsections']:
                    if polish_kleida in asubsectiondict['originaltitleline'] or polish_kleida in asubsectiondict['content']:
                        found_a_key =True
                        asubsectiondict['originaltitleline'] = asubsectiondict['originaltitleline'].replace("|pl|"+polish_kleida,"|pl")

                        asubsectiondict['content'] = asubsectiondict['content'].replace("|pl|"+polish_kleida,"|pl")
                if found_a_key:
                    sections[-1]['changes'] += '\nαφαιρέθηκε κλείδα pl'


if __name__ == '__main__':
    pagetitle = "καλός"
    with open(pagetitle,'rt') as f:
        wikitext = f.read()
    sections = get_Sections(pagetitle, wikitext, languages, parts, sortkeymaps)
    print("********** ORIGINAL? **********")
    print(sections[-1])
    create_good_lang_changes(sections)
    print("********** RECONSTRUCTED **********")
    print(text_from_sections(sections))