#!/usr/bin/python

#------------------------------------------------------------------------------------
# Utilisation : python3 BaO2-regexp.py chemin/du/repertoire rubrique
# argv[1] = chemin/du/repertoire, ex. /fils-rss-2020
# argv[2] = 3208

import os, sys, re
import time

# Pour compter le temps de fonctionnement...
start = time.time()

#-----------------------

# Fonction pour parcourir les fichiers fils RSS, pour extraire le contenu et le nettoyer. 
def walking_preprocessing_directories(path):
    # Récuperations des fichiers texte grâce au module et la fonction walk.
    for dirpath, dirnames, files in sorted(os.walk(path)):
        for file in files:
            # On traite seulement les fichiers xml
            if re.search(rf'{rubrique}.+\.xml', file):
                global i 
                i+= 1
                file_path = dirpath + "/" + file
                print (i, "Traitement de {}".format(file_path))
                # Récuperation de titres, de dates et de descriptions avec regexps
                with open(file_path, encoding="utf-8") as xmlfile:
                    text = re.findall(r'<item><title>(.+?)<\/title>.+?<description>(.+?)<\/description><guid.+?\/(\d{4}\/\d{2}\/\d{2}).+?<\/guid>', xmlfile.read())
                    # On regarde si les tuples (titre et description) n'ont pas été extraits avant un utilisant un set (ensemble) qui élimine les doublons automatiquement.
                    for tuple in text:
                        global no_doubles
                        if tuple[0] not in no_doubles:
                            no_doubles.add(tuple[0])
                            global nb_item
                            nb_item += 1
                            # On lance les fonctions de nettoyage sur les tuples.
                            title = text_cleaning(tuple[0])
                            description = text_cleaning(tuple[1])
                            date = tuple[2]
                            # Écriture des fichier de sorties.
                            output.write("{}\n{}\n\n".format(title,description))
                            tokens_title, tokens_description = tokenization(title,description)
                            output_xml.write("<item date=\"{}\">\n".format(date))
                            output_xml.write("<titre>\n{}</titre>\n".format(tokens_title))
                            output_xml.write("<description>\n{}</description>\n</item>\n".format(tokens_description))
#-----------------------

def tokenization (*args):
    l = []
    # Tokenisation de tous les arguments passés dans la fonction.
    for argument in args:
        # TOkenisation via fichiers intermédiares.
        with open('f_intermediate.txt',"w", encoding="utf-8") as file: file.write(argument)
        os.system("perl -f ./tree-tagger-linux-3.2.3/tokenise-utf8.pl f_intermediate.txt > f_intermediate.txt.pos")
        with open ('f_intermediate.txt.pos', encoding="utf-8") as file: l.append(file.read())
    os.system("rm f_intermediate.txt f_intermediate.txt.pos")
    return tuple(l)

#-----------------------
# Fonction de nettoyage avec regexps.
def text_cleaning(sent):
        text_clean = re.sub(r'<!\[CDATA\[','', sent)
        text_clean = re.sub(r'\]\]>$','', text_clean)
        text_clean = re.sub(r'&lt;.+?&gt;','', text_clean)
        text_clean = re.sub(r'&#38;#39;','\'', text_clean)
        text_clean = re.sub(r'#38;#34;','"', text_clean)
        text_clean = re.sub(r'$','.', text_clean)
        text_clean = re.sub(r'\.+$','.', text_clean)
        text_clean = re.sub(r'\?\.$','?', text_clean)
        text_clean = re.sub(r'&nbsp;',' ', text_clean)
        text_clean = re.sub(r'&amp;','&', text_clean)
        return text_clean
#-----------------------

def ttagger():
    # Étiquetage via TreeTagger.
    print("Tagging...\n")
    os.system("perl -f ./tree-tagger-linux-3.2.3/tokenise-utf8.pl sortie-py_{}.xml | ./tree-tagger-linux-3.2.3/bin/tree-tagger ./tree-tagger-linux-3.2.3/french-utf8.par -token -lemma -no-unknown -sgml > sortie-py-TT_{}".format(rubrique, rubrique))
    print("Création d'un fichier XML étiqueté...")
    # Conversion du fichier dans un fichier xml.
    os.system("perl ./tree-tagger-linux-3.2.3/treetagger2xml-utf8.pl sortie-py-TT_{} utf8".format(rubrique))
    with open('sortie-py-TT_{}.xml'.format(rubrique),"r", encoding="utf-8") as fichier:
        texte = fichier.read()
    texte = re.sub(r'&','&amp;', texte)
    with open('sortie-py-TT_{}.xml'.format(rubrique),"w", encoding="utf-8") as fichier: fichier.write(texte)
    os.system("rm sortie-py_{}.xml sortie-py-TT_{}".format(rubrique, rubrique))

#-----------------------
# Étiquetage UDpipe
def UDpipe_tagger():
    os.system("./udpipe-1.2.0-bin/bin-linux64/udpipe --tokenize --tokenizer=presegmented --tag --parse ./udpipe-1.2.0-bin/modeles/french-gsd-ud-2.5-191206.udpipe sortie-py_{}.txt > sortie-py-UD_{}.txt".format(rubrique,rubrique))

#----------------------- PROGRAME PRINCIPAL ---------------------------------

# Récuperation des arguments et normalisation du chemin du répertoire
repertoire = sys.argv[1]
repertoire = re.sub(r'(.+)/\$',r'\1', repertoire)
rubrique = sys.argv[2]

# Ouverture des fichier de sortie
output = open("sortie-py_{}.txt".format(rubrique),"w", encoding="UTF-8") 
output_xml = open("sortie-py_{}.xml".format(rubrique),"w", encoding="UTF-8") 

#Écriture de l'en-tête xml.
output_xml.write("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n")
output_xml.write("<corpus2020>\n")

i = 0
nb_item = 0
no_doubles = set()

print("\n--->Extraction de la rubrique {}<---\n".format(rubrique))

# Lancement de la fonction principal, fermeture des fichiers de sortie. 
walking_preprocessing_directories(repertoire)

output_xml.write("</corpus2020>\n")
output_xml.close()
output.close()

#Lancement des etiqueteurs
ttagger()
UDpipe_tagger()

end = time.time()
print("\nTemps écoulé...", end - start, "secondes")
print("\nItems traités : %d" %(nb_item))
