-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtoolbox_app.py
3254 lines (2697 loc) · 128 KB
/
toolbox_app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
from flask import Flask, abort, request, render_template, render_template_string, url_for, redirect, send_from_directory, Response, stream_with_context, session, send_file, jsonify
from werkzeug.utils import secure_filename
from werkzeug.exceptions import HTTPException
from forms import ContactForm, SearchForm
from flask_wtf import FlaskForm
from flask_wtf.csrf import CSRFProtect
from flask_babel import Babel, get_locale
from langdetect import detect_langs
import matplotlib.pyplot as plt
import math
import nltk
from nltk.tokenize import sent_tokenize, word_tokenize
from nltk import sent_tokenize
from nltk.corpus import stopwords
from nltk import ngrams
from nltk import FreqDist
from nltk import Text
from collections import Counter
from wordcloud import WordCloud
import zipfile
import os
from io import StringIO, BytesIO
import string
import random
from bs4 import BeautifulSoup
import urllib
import urllib.request
from urllib.parse import urlparse
import re
from lxml import etree
import csv
import contextualSpellCheck
import spacy
from spacy import displacy
import shutil
from pathlib import Path
import json
import collections
import textdistance
import difflib
from transformers import pipeline
import textstat
#from txt_ner import txt_ner_params
import gensim.downloader as api
from sklearn.cluster import KMeans
from sklearn.decomposition import PCA
import plotly.graph_objects as go
import numpy as np
nltk.download('punkt_tab')
nltk.download('stopwords')
nltk.download('punkt')
nltk.download('wordnet')
nltk.download('omw-1.4')
from nltk.corpus import wordnet
stop_words = set(stopwords.words('english'))
import pandas as pd
import sem
#import sem.storage
#import sem.exporters
import ocr
from cluster import freqs2clustering
UPLOAD_FOLDER = 'uploads'
MODEL_FOLDER = 'static/models'
UTILS_FOLDER = 'static/utils'
ROOT_FOLDER = Path(__file__).parent.absolute()
csrf = CSRFProtect()
SECRET_KEY = os.urandom(32)
app = Flask(__name__)
# Babel config
#def get_locale():
# return request.accept_languages.best_match(['fr', 'en'])
#babel = Babel(app, locale_selector=get_locale)
babel = Babel(app)
# App config
app.config['SESSION_TYPE'] = 'filesystem'
app.config['SECRET_KEY'] = SECRET_KEY
app.config['MAX_CONTENT_LENGTH'] = 50 * 1024 * 1024 # Limit file upload to 35MB
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MODEL_FOLDER'] = MODEL_FOLDER
app.config['UTILS_FOLDER'] = UTILS_FOLDER
app.config['LANGUAGES'] = {
'fr': 'FR',
'en': 'EN',
}
app.add_url_rule("/uploads/<name>", endpoint="download_file", build_only=True)
csrf.init_app(app)
#-----------------------------------------------------------------
# BABEL
#-----------------------------------------------------------------
@app.route('/language=<language>')
def set_language(language=None):
session['language'] = language
return redirect(url_for('index'))
def get_locale():
if request.args.get('language'):
session['language'] = request.args.get('language')
return session.get('language', 'fr')
babel.init_app(app, locale_selector=get_locale)
@app.context_processor
def inject_conf_var():
return dict(AVAILABLE_LANGUAGES=app.config['LANGUAGES'], CURRENT_LANGUAGE=session.get('language', request.accept_languages.best_match(app.config['LANGUAGES'])))
#-----------------------------------------------------------------
# ROUTES
#-----------------------------------------------------------------
@app.route('/')
def index():
return render_template('index.html')
@app.route('/pandore')
def pandore():
return render_template('pandore.html')
@app.route('/projet')
def projet():
return render_template('projet.html')
@app.route('/code_source')
def code_source():
return render_template('code_source.html')
@app.route('/contact')
def contact():
form = ContactForm()
return render_template('contact.html', form=form)
@app.route('/copyright')
def copyright():
return render_template('copyright.html')
#-----------------------------------------------------------------
# DOCUMENTATION
#-----------------------------------------------------------------
@app.route('/documentation')
def documentation():
return render_template('documentation.html')
@app.route('/documentation_recognition')
def documentation_recognition():
return render_template('documentation/documentation_recognition.html')
@app.route('/documentation_preprocessing')
def documentation_preprocessing():
return render_template('documentation/documentation_preprocessing.html')
@app.route('/documentation_conversion')
def documentation_conversion():
return render_template('documentation/documentation_conversion.html')
@app.route('/documentation_annotation')
def documentation_annotation():
return render_template('documentation/documentation_annotation.html')
@app.route('/documentation_extraction')
def documentation_extraction():
return render_template('documentation/documentation_extraction.html')
@app.route('/documentation_analyses')
def documentation_analyses():
return render_template('documentation/documentation_analyses.html')
@app.route('/documentation_correction')
def documentation_correction():
return render_template('documentation/documentation_correction.html')
@app.route('/documentation_workflow')
def documentation_workflow():
return render_template('documentation/documentation_workflow.html')
@app.route('/documentation_generation')
def documentation_generation():
return render_template('documentation/documentation_generation.html')
#-----------------------------------------------------------------
# TUTORIELS
#-----------------------------------------------------------------
@app.route('/tutoriel')
def tutoriel():
return render_template('tutoriel.html')
@app.route('/tutoriel_conversion')
def tutoriel_conversion():
return render_template('tutoriel/tutoriel_conversion.html')
@app.route('/tutoriel_annotation')
def tutoriel_annotation():
return render_template('tutoriel/tutoriel_annotation.html')
@app.route('/tutoriel_extraction')
def tutoriel_extraction():
return render_template('tutoriel/tutoriel_extraction.html')
@app.route('/tutoriel_analyses')
def tutoriel_analyses():
return render_template('tutoriel/tutoriel_analyses.html')
@app.route('/tutoriel_correction')
def tutoriel_correction():
return render_template('tutoriel/tutoriel_correction.html')
@app.route('/tutoriel_workflow')
def tutoriel_workflow():
return render_template('tutoriel/tutoriel_workflow.html')
@app.route('/tutoriel_generation')
def tutoriel_generation():
return render_template('tutoriel/tutoriel_generation.html')
#-----------------------------------------------------------------
# TACHES
#-----------------------------------------------------------------
@app.route('/atr_tools')
def atr_tools():
return render_template('taches/atr_tools.html')
@app.route('/pretraitement')
def pretraitement():
return render_template('taches/pretraitement.html')
@app.route('/conversion')
def conversion():
return render_template('taches/conversion.html')
@app.route('/annotation_automatique')
def annotation_automatique():
return render_template('taches/annotation_automatique.html')
@app.route('/extraction_information')
def extraction_information():
return render_template('taches/extraction_information.html')
@app.route('/analyses')
def analyses():
return render_template('taches/analyses.html')
@app.route('/search_tools')
def search_tools():
return render_template('taches/search_tools.html')
@app.route('/outils_visualisation')
def outils_visualisation():
return render_template('taches/visualisation.html')
@app.route('/outils_corpus')
def outils_corpus():
return render_template('taches/corpus.html')
@app.route('/collecter_corpus')
def collecter_corpus():
return render_template('taches/collecter_corpus.html')
@app.route('/outils_pipeline')
def outils_pipeline():
return render_template('taches/pipeline.html')
@app.route('/generation_texte')
def generation_texte():
return render_template('taches/generation_texte.html')
#-----------------------------------------------------------------
# OUTILS
#-----------------------------------------------------------------
@app.route('/numeriser')
def numeriser():
form = FlaskForm()
return render_template('outils/numeriser.html', form=form)
@app.route('/speech')
def speech():
form = FlaskForm()
return render_template('outils/speech.html', form=form)
@app.route('/nettoyage_texte')
def nettoyage_texte():
form = FlaskForm()
return render_template('outils/nettoyage_texte.html', form=form)
@app.route('/text_normalisation')
def text_normalisation():
form = FlaskForm()
return render_template('outils/text_normalisation.html', form=form)
@app.route('/separation_texte')
def separation_texte():
form = FlaskForm()
return render_template('outils/separation_texte.html', form=form)
@app.route('/conversion_xml')
def conversion_xml():
form = FlaskForm()
return render_template('outils/conversion_xml.html', form=form)
@app.route('/entites_nommees')
def entites_nommees():
form = FlaskForm()
return render_template('outils/entites_nommees.html', form=form)
@app.route('/etiquetage_morphosyntaxique')
def etiquetage_morphosyntaxique():
form = FlaskForm()
err = ""
return render_template('outils/etiquetage_morphosyntaxique.html', form=form, err=err)
@app.route('/categories_semantiques')
def categories_semantiques():
return render_template('outils/categories_semantiques.html')
@app.route('/extraction_mots_cles')
def extraction_mots_cles():
form = FlaskForm()
return render_template('outils/extraction_mots_cles.html', form=form, res={})
@app.route('/quotation_extraction')
def quotation_extraction():
form = FlaskForm()
return render_template('outils/quotation_extraction.html', form=form)
@app.route('/topic_modelling')
def topic_modelling():
form = FlaskForm()
return render_template('outils/topic_modelling.html', form=form, res={})
@app.route('/analyse_linguistique')
def analyse_linguistique():
form = FlaskForm()
return render_template('outils/analyse_linguistique.html', form=form)
@app.route('/analyse_statistique')
def analyse_statistique():
form = FlaskForm()
return render_template('outils/analyse_statistique.html', form=form)
@app.route('/analyse_lexicale')
def analyse_lexicale():
form = FlaskForm()
return render_template('outils/analyse_lexicale.html', form=form)
@app.route('/analyse_texte')
def analyse_texte():
form = FlaskForm()
return render_template('outils/analyse_texte.html', form=form)
@app.route('/comparison')
def comparison():
form = FlaskForm()
return render_template('outils/comparison.html', form=form)
@app.route('/embeddings')
def embeddings():
form = FlaskForm()
return render_template('outils/embeddings.html', form=form)
@app.route('/tanagra')
def tanagra():
return render_template('outils/tanagra.html')
@app.route('/renard')
def renard():
form = FlaskForm()
return render_template('outils/renard.html', form=form, graph="", fname="")
@app.route('/extraction_gallica')
def extraction_gallica():
form = FlaskForm()
return render_template('outils/extraction_gallica.html', form=form)
@app.route('/extraction_wikisource')
def extraction_wikisource():
form = FlaskForm()
return render_template('outils/extraction_wikisource.html', form=form)
@app.route('/correction_erreur')
def correction_erreur():
form = FlaskForm()
return render_template('outils/correction_erreur.html', form=form)
@app.route('/normalisation')
def normalisation():
return render_template('outils/normalisation.html')
@app.route('/ocr_ner')
def ocr_ner():
form = FlaskForm()
return render_template('outils/ocr_ner.html', form=form)
@app.route('/ocr_map')
def ocr_map():
form = FlaskForm()
return render_template('outils/ocr_map.html', form=form)
@app.route('/text_completion')
def text_completion():
form = FlaskForm()
return render_template('outils/text_completion.html', form=form)
@app.route('/qa_and_conversation')
def qa_and_conversation():
form = FlaskForm()
return render_template('outils/qa_and_conversation.html', form=form)
@app.route('/translation')
def translation():
form = FlaskForm()
return render_template('outils/translation.html', form=form)
@app.route('/adjusting_text_readibility_level')
def adjusting_text_readibility_level():
form = FlaskForm()
return render_template('outils/adjusting_text_readibility_level.html', form=form)
@app.route('/resume_automatique')
def resume_automatique():
return render_template('outils/resume_automatique.html')
#-----------------------------------------------------------------
# ERROR HANDLERS
#-----------------------------------------------------------------
@app.errorhandler(500)
def internal_server_error(e):
return render_template('500.html'), 500
@app.errorhandler(413)
def file_too_big(e):
return render_template('413.html'), 413
@app.errorhandler(Exception)
def handle_exception(e):
# pass through HTTP errors
if isinstance(e, HTTPException):
return e
# now you're handling non-HTTP exceptions only
return render_template("500_custom.html", e=e), 500
#-----------------------------------------------------------------
# FONCTIONS
#-----------------------------------------------------------------
@app.route('/send_msg', methods=["GET","POST"])
def send_msg():
if request.method == 'POST':
name = request.form["name"]
email = request.form["email"]
message = request.form["message"]
res = pd.DataFrame({'name':name, 'email':email,'message':message}, index=[0])
res.to_csv('./contactMsg.csv')
return render_template('validation_contact.html')
return render_template('contact.html', form=form)
# TELECHARGEMENT DE FICHIER
@app.route('/download')
def download():
path = 'static/textolab.zip'
return send_file(path, as_attachment=True)
#-----------------------------------------------------------------
# Numérisation
#-----------------------------------------------------------------
# NUMERISATION TESSERACT
@app.route('/run_tesseract', methods=["GET","POST"])
@stream_with_context
def run_tesseract():
if request.method == 'POST':
uploaded_files = request.files.getlist("tessfiles")
model = request.form['tessmodel']
if 'model2' in request.form:
model_bis = request.form['model2']
else:
model_bis = ''
up_folder = app.config['UPLOAD_FOLDER']
rand_name = 'ocr_' + ''.join((random.choice(string.ascii_lowercase) for x in range(8)))
text = ocr.tesseract_to_txt(uploaded_files, model, model_bis, rand_name, ROOT_FOLDER, up_folder)
response = Response(text, mimetype='text/plain',
headers={"Content-disposition": "attachment; filename=" + rand_name + '.txt'})
return response
return render_template('numeriser.html', erreur=erreur)
#-----------------------------------------------------------------
# Prétraitement
#-----------------------------------------------------------------
#-------------- Nettoyage de texte -------------------------
# Importer les stopwords pour chaque langue
stop_words_english = set(stopwords.words('english'))
stop_words_french = set(stopwords.words('french'))
stop_words_spanish = set(stopwords.words('spanish'))
stop_words_german = set(stopwords.words('german'))
stop_words_danish = set(stopwords.words('danish'))
stop_words_finnish = set(stopwords.words('finnish'))
stop_words_greek = set(stopwords.words('greek'))
stop_words_italian = set(stopwords.words('italian'))
stop_words_dutch = set(stopwords.words('dutch'))
#stop_words_polish = set(stopwords.words('polish'))
stop_words_portuguese = set(stopwords.words('portuguese'))
stop_words_russian = set(stopwords.words('russian'))
# Fonction pour obtenir les stopwords en fonction de la langue
def get_stopwords(language):
if language == 'english':
return stop_words_english
elif language == 'french':
return stop_words_french
elif language == 'spanish':
return stop_words_spanish
elif language == 'german':
return stop_words_german
elif language == 'danish':
return stop_words_danish
elif language == 'finnish':
return stop_words_finnish
elif language == 'greek':
return stop_words_greek
elif language == 'italian':
return stop_words_italian
elif language == 'dutch':
return stop_words_dutch
elif language == 'portuguese':
return stop_words_portuguese
elif language == 'russian':
return stop_words_russian
else:
return set()
@app.route('/removing_elements', methods=['POST'])
def removing_elements():
if 'files' not in request.files:
response = {"error": "No files part"}
return Response(json.dumps(response), status=400, mimetype='application/json')
files = request.files.getlist('files')
if not files or all(file.filename == '' for file in files):
response = {"error": "No selected files"}
return Response(json.dumps(response), status=400, mimetype='application/json')
removing_type = request.form['removing_type']
selected_language = request.form['selected_language']
rand_name = 'removing_' + ''.join(random.choice(string.ascii_lowercase) for x in range(5))
result_path = os.path.join(os.getcwd(), rand_name)
os.makedirs(result_path, exist_ok=True)
for f in files:
try:
input_text = f.read().decode('utf-8')
tokens = word_tokenize(input_text)
removing_punctuation = [token for token in tokens if token.isalpha()]
stop_words = get_stopwords(selected_language)
removing_stopwords = [token for token in tokens if token.lower() not in stop_words]
filename, file_extension = os.path.splitext(f.filename)
if removing_type == 'punctuation':
output_name = filename + '_punctuation.txt'
with open(os.path.join(result_path, output_name), 'w', encoding='utf-8') as out:
out.write('The original text was :\n"' + input_text + '"\n\nThe text without punctuation is :\n"' + " ".join(removing_punctuation) + '"')
elif removing_type == 'stopwords':
output_name = filename + '_stopwords.txt'
with open(os.path.join(result_path, output_name), 'w', encoding='utf-8') as out:
out.write('The original text was :\n"' + input_text + '"\n\nThe text without stopwords is :\n"' + " ".join(removing_stopwords) + '"')
finally:
f.close()
if len(os.listdir(result_path)) > 0:
shutil.make_archive(result_path, 'zip', result_path)
output_stream = BytesIO()
with open(str(result_path) + '.zip', 'rb') as res:
content = res.read()
output_stream.write(content)
response = Response(output_stream.getvalue(), mimetype='application/zip',
headers={"Content-disposition": "attachment; filename=" + rand_name + '.zip'})
output_stream.seek(0)
output_stream.truncate(0)
shutil.rmtree(result_path)
os.remove(str(result_path) + '.zip')
return response
return Response(json.dumps({"error": "Une erreur est survenue dans le traitement des fichiers."}), status=500, mimetype='application/json')
#-------------- Normalisation de texte -------------------------
nlp_eng = spacy.load('en_core_web_sm')
nlp_fr = spacy.load('fr_core_news_sm')
nlp_es = spacy.load('es_core_news_sm')
nlp_de = spacy.load('de_core_news_sm')
nlp_it = spacy.load('it_core_news_sm')
nlp_da = spacy.load("da_core_news_sm")
nlp_nl = spacy.load("nl_core_news_sm")
nlp_fi = spacy.load("fi_core_news_sm")
nlp_pl = spacy.load("pl_core_news_sm")
nlp_pt = spacy.load("pt_core_news_sm")
nlp_el = spacy.load("el_core_news_sm")
nlp_ru = spacy.load("ru_core_news_sm")
def get_nlp(language):
if language == 'english':
return nlp_eng
elif language == 'french':
return nlp_fr
elif language == 'spanish':
return nlp_es
elif language == 'german':
return nlp_de
elif language == 'italian':
return nlp_it
elif language == 'danish':
return nlp_da
elif language == 'dutch':
return nlp_nl
elif language == 'finnish':
return nlp_fi
elif language == 'polish':
return nlp_pl
elif language == 'portuguese':
return nlp_pt
elif language == 'greek':
return nlp_el
elif language == 'russian':
return nlp_ru
else:
return set()
@app.route('/normalize_text', methods=['POST'])
def normalize_text():
if 'files' not in request.files:
response = {"error": "No files part"}
return Response(json.dumps(response), status=400, mimetype='application/json')
files = request.files.getlist('files')
if not files or all(file.filename == '' for file in files):
response = {"error": "No selected files"}
return Response(json.dumps(response), status=400, mimetype='application/json')
normalisation_type = request.form['normalisation_type']
selected_language = request.form['selected_language']
rand_name = 'normalized_' + ''.join(random.choice(string.ascii_lowercase) for x in range(5))
result_path = os.path.join(os.getcwd(), rand_name)
os.makedirs(result_path, exist_ok=True)
for f in files:
try:
input_text = f.read().decode('utf-8')
tokens = word_tokenize(input_text)
lowers = [token.lower() for token in tokens]
nlp = get_nlp(selected_language)
lemmas = [token.lemma_ for token in nlp(input_text)]
filename, file_extension = os.path.splitext(f.filename)
if normalisation_type == 'tokens':
output_name = filename + '_tokens.txt'
with open(os.path.join(result_path, output_name), 'w', encoding='utf-8') as out:
out.write("The tokens of the text are: " + ", ".join(tokens))
elif normalisation_type == 'lowercases':
output_name = filename + '_lower.txt'
with open(os.path.join(result_path, output_name), 'w', encoding='utf-8') as out:
out.write("The lowercase version of the text is: " + ", ".join(lowers))
elif normalisation_type == 'lemmas':
output_name = filename + '_lemmas.txt'
with open(os.path.join(result_path, output_name), 'w', encoding='utf-8') as out:
out.write("The lemmas of the text are: " + ", ".join(lemmas))
finally:
f.close()
if len(os.listdir(result_path)) > 0:
shutil.make_archive(result_path, 'zip', result_path)
output_stream = BytesIO()
with open(str(result_path) + '.zip', 'rb') as res:
content = res.read()
output_stream.write(content)
response = Response(output_stream.getvalue(), mimetype='application/zip',
headers={"Content-disposition": "attachment; filename=" + rand_name + '.zip'})
output_stream.seek(0)
output_stream.truncate(0)
shutil.rmtree(result_path)
os.remove(str(result_path) + '.zip')
return response
return Response(json.dumps({"error": "Une erreur est survenue dans le traitement des fichiers."}), status=500, mimetype='application/json')
#-------------- Séparation de texte -------------------------
@app.route('/split_sentences', methods=['POST'])
def split_sentences():
if 'files' not in request.files:
response = {"error": "No files part"}
return Response(json.dumps(response), status=400, mimetype='application/json')
files = request.files.getlist('files')
if not files or all(file.filename == '' for file in files):
response = {"error": "No selected files"}
return Response(json.dumps(response), status=400, mimetype='application/json')
rand_name = 'splitsentences_' + ''.join(random.choice(string.ascii_lowercase) for x in range(5))
result_path = os.path.join(os.getcwd(), rand_name)
os.makedirs(result_path, exist_ok=True)
for f in files:
try:
input_text = f.read().decode('utf-8')
tokens = word_tokenize(input_text)
sentences = nltk.sent_tokenize(input_text)
splitsentence = [sentence.strip() for sentence in sentences]
filename, file_extension = os.path.splitext(f.filename)
output_name = filename + '.txt'
with open(os.path.join(result_path, output_name), 'w', encoding='utf-8') as out:
out.write("The sentences of the text are: " + ",\n".join(splitsentence))
finally:
f.close()
if len(os.listdir(result_path)) > 0:
shutil.make_archive(result_path, 'zip', result_path)
output_stream = BytesIO()
with open(str(result_path) + '.zip', 'rb') as res:
content = res.read()
output_stream.write(content)
response = Response(output_stream.getvalue(), mimetype='application/zip',
headers={"Content-disposition": "attachment; filename=" + rand_name + '.zip'})
output_stream.seek(0)
output_stream.truncate(0)
shutil.rmtree(result_path)
os.remove(str(result_path) + '.zip')
return response
return Response(json.dumps({"error": "Une erreur est survenue dans le traitement des fichiers."}), status=500, mimetype='application/json')
#-----------------------------------------------------------------
# Conversion XML
#-----------------------------------------------------------------
@app.route('/xmlconverter', methods=["GET", "POST"])
@stream_with_context
def xmlconverter():
if request.method == 'POST':
fields = {}
fields['title'] = request.form['title']
fields['title_lang'] = request.form['title_lang'] # required
fields['author'] = request.form.get('author')
fields['respStmt_name'] = request.form.get('nameresp')
fields['respStmt_resp'] = request.form.get('resp')
fields['pubStmt'] = request.form['pubStmt'] # required
fields['sourceDesc'] = request.form['sourceDesc'] # required
fields['revisionDesc_change'] = request.form['change']
fields['change_who'] = request.form['who']
fields['change_when'] = request.form['when']
fields['licence'] = request.form['licence']
fields['divtype'] = request.form['divtype']
fields["creation"] = request.form['creation']
fields["lang"] = request.form['lang']
fields["projet_p"] = request.form['projet_p']
fields["edit_correction_p"] = request.form['edit_correction_p']
fields["edit_hyphen_p"] = request.form['edit_hyphen_p']
files = request.files.getlist('file')
zip_buffer = BytesIO()
with zipfile.ZipFile(zip_buffer, 'a', zipfile.ZIP_DEFLATED, False) as zip_file:
for f in files:
filename = secure_filename(f.filename)
path_to_file = os.path.join(app.config['UPLOAD_FOLDER'], filename)
f.save(path_to_file)
try:
with open(path_to_file, "r") as file:
for l in file:
break
# Returning xml string
root = txt_to_xml(path_to_file, fields)
# Writing in stream
output_stream = BytesIO()
output_filename = os.path.splitext(filename)[0] + '.xml'
etree.ElementTree(root).write(output_stream, xml_declaration=True, encoding="utf-8")
output_stream.seek(0)
zip_file.writestr(output_filename, output_stream.getvalue())
output_stream.truncate(0)
except UnicodeDecodeError:
return 'format de fichier incorrect'
zip_buffer.seek(0)
return send_file(zip_buffer, mimetype='application/zip', as_attachment=True, download_name='encoded_files.zip')
return render_template("/conversion_xml")
# CONVERSION XML-TEI
# Construit un fichier TEI à partir des métadonnées renseignées dans le formulaire.
# Renvoie le chemin du fichier ainsi créé
# Paramètres :
# - filename : emplacement du fichier uploadé par l'utilisateur
# - fields : dictionnaire des champs présents dans le form metadata
import xml.etree.ElementTree as etree
def encode_text(filename, is_text_standard=True, is_poem=False, is_play=False, is_book=False):
div = etree.Element("div")
with open(filename, "r", encoding="utf-8") as f:
lines = f.readlines()
if is_poem:
stanza = []
for line in lines:
if line.strip() == "":
if stanza:
stanza_element = etree.Element("lg", type="stanza")
for verse in stanza:
verse_element = etree.Element("l")
verse_element.text = verse.strip()
stanza_element.append(verse_element)
div.append(stanza_element)
stanza = []
else:
stanza.append(line)
if stanza:
stanza_element = etree.Element("lg", type="stanza")
for verse in stanza:
verse_element = etree.Element("l")
verse_element.text = verse.strip()
stanza_element.append(verse_element)
div.append(stanza_element)
elif is_play:
scene = []
acte_element = None
scene_element = None
for line in lines:
if re.match(r"Act|Acte", line.strip()):
if acte_element is not None:
div.append(acte_element)
acte_element = etree.Element("div")
acte_element.set("type", "act")
head_element = etree.Element("head")
head_element.text = line.strip()
acte_element.append(head_element)
scene = []
elif re.match(r"Scène|Scene", line.strip()):
if scene_element is not None:
acte_element.append(scene_element)
scene_element = etree.Element("div")
scene_element.set("type", "scene")
head_element = etree.Element("head")
head_element.text = line.strip()
scene_element.append(head_element)
scene = []
else:
scene.append(line)
if scene_element is not None:
for dialogue in scene:
dialogue_element = etree.Element("p")
dialogue_element.text = dialogue.strip()
scene_element.append(dialogue_element)
acte_element.append(scene_element)
if acte_element is not None:
div.append(acte_element)
elif is_book:
scene = []
chapter_element = None
text_element = None
for line in lines:
if re.match(r"Chapter|Chapitre", line.strip()):
if chapter_element is not None:
div.append(chapter_element)
chapter_element = etree.Element("div")
chapter_element.set("type", "chapter")
head_element = etree.Element("head")
head_element.text = line.strip()
chapter_element.append(head_element)
scene = []
else:
scene.append(line)
if chapter_element is not None:
text_element = etree.Element("div")
text_element.set("type", "text")
for dialogue in scene:
dialogue_element = etree.Element("p")
dialogue_element.text = dialogue.strip()
text_element.append(dialogue_element)
chapter_element.append(text_element)
div.append(chapter_element)
else:
file = "".join(lines)
file = file.replace(".\n", ".[$]")
ptext = file.split("[$]")
for line in ptext:
paragraph = etree.Element("p")
paragraph.text = line.strip()
div.append(paragraph)
return div
def txt_to_xml(filename, fields):
# Initialise TEI
root = etree.Element("TEI", {'xmlns': "http://www.tei-c.org/ns/1.0"})
# TEI header
teiHeader = etree.Element("teiHeader")
fileDesc = etree.Element("fileDesc")
titleStmt = etree.Element("titleStmt")
editionStmt = etree.Element("editionStmt")
publicationStmt = etree.Element("publicationStmt")
sourceDesc = etree.Element("sourceDesc")
profileDesc = etree.Element("profileDesc")
encodingDesc = etree.Element("encodingDesc")
revisionDesc = etree.Element("revisionDesc")
#- TitleStmt
#-- Title
title = etree.Element("title")
title_lang = fields["title_lang"]
title.set("{http://www.w3.org/XML/1998/namespace}lang", title_lang)
title.text = fields['title']
titleStmt.append(title)
#-- Author
if fields['author']:
author = etree.Element("author")
author.text = fields['author']
titleStmt.append(author)
#- EditionStmt
#-- respStmt
if fields['respStmt_resp']:
respStmt = etree.Element("respStmt")
resp = etree.Element("resp")
resp.text = fields['respStmt_resp']
respStmt.append(resp)
if fields['respStmt_name']:
name = etree.Element("name")
name.text = fields['respStmt_name']
respStmt.append(name)
titleStmt.append(respStmt)
#- PublicationStmt
publishers_list = fields['pubStmt'].split('\n') # Get publishers list
publishers_list = list(map(str.strip, publishers_list)) # remove trailing characters
publishers_list = [x for x in publishers_list if x] # remove empty strings
for pub in publishers_list:
publisher = etree.Element("publisher")
publisher.text = pub
publicationStmt.append(publisher)
licence = etree.Element("licence")
availability = etree.Element("availability")
licence.text = fields["licence"]
if licence.text == "CC-BY":
licence.set("target", "https://creativecommons.org/licenses/by/4.0/")
if licence.text == "CC-BY-SA":