File size: 13,432 Bytes
f347e77
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# if you are in production install waitress (pip install waitress) and put this code
"""from waitress import server
    serve(app, host="0.0.0.0", port=8081) """
# before to run the app

# IMPORTATION DES BIBLIOHEQUES
import os
import sys
import cv2  # pip install opencv-python ...................................................
import numpy as np  # pip install numpy ......................................................
import tensorflow as tf
from flask import Flask, request, render_template, jsonify
from flask_cors import CORS
from pdf2image import convert_from_path
import utils.prediction as pred  # importion de notre module python de prediction

# INTIALISATION DE FLASK
app = Flask(__name__)
"""app.secret_key = "joelhhybghbgfgy"
CORS(app, support_credentials=True)
app.config['CORS_HEADERS'] = 'Content-Type"""

# CONFIGURATION DES CHEMINS ET CHARGEMENT DU MODELE
"""app.config['UPLOAD_PATH'] = "UPLOAD_FOLDER"
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024"""
courant = os.path.abspath(os.path.dirname(sys.argv[0]))

ALLOWED_EXTENSIONS = {"txt", "pdf", "png", "jpg", "jpeg", "gif"}


# FONCTION POUR UNE ROUTE QUI N'EXISTE PAS
@app.errorhandler(404)
def page_not_found(error):
    return render_template("errors/404.html"), 404


# FONCTION UPLOAD PLUS PREDICTION DE DOCUMENTS PDF COMME IMAGE
@app.route("/predict_files", methods=["POST"])
def predict_files():

    # RECUPERATION DES DOC DANS UN FORMDATA AVEC 'files' COMME CLE DE CHAMP
    files = request.files.getlist("files")
    resultat = []
    Extraction_caractere = "Pas disponible"
    for file in files:

        # determination du type de document if pdf else si image
        name = file.filename
        name_type = name.split(".")[-1].lower()

        # si le document est un pdf
        if name_type == "pdf":

            # stocker le fichier dans le repertoire temporaire data
            file.save(os.path.join(courant + "/data/", file.filename))

            # convertir le fichier en image avec pdf2image
            pages = convert_from_path(
                os.path.join(courant + "/data/", file.filename), dpi=200
            )

            # suppression du pdf
            os.remove(os.path.join(courant + "/data/" + name))

            # stocker les images PIL de pages dans data
            for idx, page in enumerate(pages):
                page.save(
                    os.path.join(
                        courant + "/data/", str(file.filename) + str(idx) + ".jpg"
                    )
                )

            # recuperation des images et prediction
            for idx, page in enumerate(pages):

                # lecture de l'image et premiere prediction
                npimg = np.fromfile(
                    os.path.join(
                        courant + "/data/" + str(file.filename) + str(idx) + ".jpg"
                    ),
                    np.uint8,
                )
                output = pred.class_prediction(npimg)

                # plus de precision sur la nature des documents
                if output["CLASSE"] == "Justificatif d'identité":
                    Detail_output = pred.ID_prediction(npimg)
                    # si le justificatif est une piece d'identité alors on appelle la fonction d'extraction
                    # de caractere de la cni
                    if Detail_output["CLASSE"] == "CARTE D'IDENTITE":
                        Extraction_caractere = pred.CNI_Extraction(pred.ImgRogne(npimg))

                elif output["CLASSE"] == "Justificatif d'adresse":
                    Detail_output = pred.ADR_prediction(npimg)

                else:
                    Detail_output = pred.REV_prediction(npimg)

                resultat.append(
                    [
                        {
                            "FAMILLE": output,
                            "NATURE": Detail_output,
                            "EXTRACTION": Extraction_caractere,
                        }
                    ]
                )
                output = ""
            output = ""

            # suppression des images
            for idx, page in enumerate(pages):
                os.remove(
                    os.path.join(
                        courant + "/data/", str(file.filename) + str(idx) + ".jpg"
                    )
                )

        else:  # si cest une image
            npimg = np.fromfile(file, np.uint8)  # lecture de l'image
            output = pred.class_prediction(npimg)

            # plus de precision sur la nature des documents
            if output["CLASSE"] == "Justificatif d'identité":
                Detail_output = pred.ID_prediction(npimg)
                # si le justificatif est une piece d'identité alors on appelLe la fonction d'extraction
                # de caractere de la cni
                if Detail_output["CLASSE"] == "CARTE D'IDENTITE":
                    Extraction_caractere = pred.CNI_Extraction(pred.ImgRogne(npimg))

            elif output["CLASSE"] == "Justificatif d'adresse":
                Detail_output = pred.ADR_prediction(npimg)

            else:
                Detail_output = pred.REV_prediction(npimg)

            resultat.append(
                [
                    {
                        "FAMILLE": output,
                        "NATURE": Detail_output,
                        "EXTRACTION": Extraction_caractere,
                    }
                ]
            )

    return jsonify(resultat)


# FONCTION CLASSIFICATION DE DOCUMENTS PDF COMME IMAGE
@app.route("/classifications", methods=["POST"])
def classifications():
    files = request.files.getlist("files")

    # initialisation des listes
    resultat = []
    ADR_nature = []
    REV_nature = []
    ID_nature = []

    for file in files:

        # determination du type de document if pdf else si image
        name = file.filename
        name_type = name.split(".")[-1].lower()

        # si le document est un pdf
        if name_type == "pdf":
            # stocker le fichier dans le repertoire temporaire data
            file.save(os.path.join(courant + "/data/", file.filename))

            # convertir le fichier en image avec pdf2image
            pages = convert_from_path(
                os.path.join(courant + "/data/", file.filename), dpi=200
            )

            # suppression du pdf
            os.remove(os.path.join(courant + "/data/" + name))

            # stocker les images PIL de pages dans data
            for idx, page in enumerate(pages):
                page.save(
                    os.path.join(
                        courant + "/data/", str(file.filename) + str(idx) + ".jpg"
                    )
                )

            # recuperation des images et prediction
            for idx, page in enumerate(pages):

                # lecture de l'image
                npimg = np.fromfile(
                    os.path.join(
                        courant + "/data/" + str(file.filename) + str(idx) + ".jpg"
                    ),
                    np.uint8,
                )
                output = pred.class_prediction(npimg)

                # plus de precision sur la nature des documents pour une classification plus detaillée
                # pour les justificatifs d'identité
                if output["CLASSE"] == "Justificatif d'identité":
                    Detail_output = pred.ID_prediction(npimg)

                    # ajout des information de prediction dans un json
                    ID_nature.append(
                        {
                            "NOM": str(file.filename) + str(idx) + ".jpg",
                            "FAMILLE": output,
                            "NATURE": Detail_output,
                        }
                    )
                # pour les justificatifs d'adresse
                elif output["CLASSE"] == "Justificatif d'adresse":
                    Detail_output = pred.ADR_prediction(npimg)

                    # ajout des information de pridiction dans un json
                    ADR_nature.append(
                        {
                            "NOM": str(file.filename) + str(idx) + ".jpg",
                            "FAMILLE": output,
                            "NATURE": Detail_output,
                        }
                    )

                # pour les justificatifs de revenu
                else:
                    Detail_output = pred.REV_prediction(npimg)

                    # ajout des information de prEdiction dans un json
                    REV_nature.append(
                        {
                            "NOM": str(file.filename) + str(idx) + ".jpg",
                            "FAMILLE": output,
                            "NATURE": Detail_output,
                        }
                    )
                output = ""
            output = ""

            # suppression des images
            for idx, page in enumerate(pages):
                os.remove(
                    os.path.join(
                        courant + "/data/", str(file.filename) + str(idx) + ".jpg"
                    )
                )

        else:  # si cest une image
            npimg = np.fromfile(file, np.uint8)
            output = pred.class_prediction(npimg)

            # pour les justificatifs d'identite
            if output["CLASSE"] == "Justificatif d'identité":
                Detail_output = pred.ID_prediction(npimg)

                # ajout des information de pridiction dans un json
                ID_nature.append(
                    {
                        "NOM": str(file.filename),
                        "FAMILLE": output,
                        "NATURE": Detail_output,
                    }
                )

            # pour les justificatifs d'adresse
            elif output["CLASSE"] == "Justificatif d'adresse":
                Detail_output = pred.ADR_prediction(npimg)

                # ajout des information de pridiction dans un json
                ADR_nature.append(
                    {
                        "NOM": str(file.filename),
                        "FAMILLE": output,
                        "NATURE": Detail_output,
                    }
                )

            # pour les justificatifs de revenu
            else:
                Detail_output = pred.REV_prediction(npimg)

                # ajout des information de pridiction dans un json
                REV_nature.append(
                    {
                        "NOM": str(file.filename),
                        "FAMILLE": output,
                        "NATURE": Detail_output,
                    }
                )
            output = ""

        # le fichier json fichier regroupant toute les information
    resultat.append({"ID": ID_nature, "ADR": ADR_nature, "REV": REV_nature})

    return jsonify(resultat)


# FONCTION EXTRACTION VIVA DE DOCUMENTS PDF COMME IMAGE
@app.route("/visa_extraction", methods=["POST"])
def visa_extraction():

    # RECUPERATION DES DOC DANS UN FORMDATA AVEC 'files' COMME CLE DE CHAMP
    files = request.files.getlist("files")
    resultat = []
    for file in files:

        # determination du type de document if pdf else si image
        name = file.filename
        name_type = name.split(".")[-1].lower()

        # si le document est un pdf
        if name_type == "pdf":

            # stocker le fichier dans le repertoire temporaire data
            file.save(os.path.join(courant + "/data/", file.filename))

            # convertir le fichier en image avec pdf2image
            pages = convert_from_path(
                os.path.join(courant + "/data/", file.filename), dpi=200
            )

            # suppression du pdf
            os.remove(os.path.join(courant + "/data/" + name))

            # stocker les images PIL de pages dans data
            for idx, page in enumerate(pages):
                page.save(
                    os.path.join(
                        courant + "/data/", str(file.filename) + str(idx) + ".jpg"
                    )
                )

            # recuperation des images et prediction
            for idx, page in enumerate(pages):

                # lecture de l'image et premiere prediction
                npimg = np.fromfile(
                    os.path.join(
                        courant + "/data/" + str(file.filename) + str(idx) + ".jpg"
                    ),
                    np.uint8,
                )
                output = pred.VISA_Extraction(pred.ImgRogne(npimg))

                # ajout des information d'extraction dans un json
                resultat.append(
                    {
                        "NOM": output,
                    }
                )
                output = ""
            output = ""

            # suppression des images
            for idx, page in enumerate(pages):
                os.remove(
                    os.path.join(
                        courant + "/data/", str(file.filename) + str(idx) + ".jpg"
                    )
                )

        else:  # si cest une image
            npimg = np.fromfile(file, np.uint8)  # lecture de l'image
            output = pred.VISA_Extraction(pred.ImgRogne(npimg))

            resultat.append(
                {
                    "NOM": output,
                }
            )

    return jsonify(resultat)


if __name__ == "__main__":
    app.run(host="0.0.0.0", port=8081, debug=True)
    # app.run(debug=True)